2010-08-05 6 views
0
class Book < ActiveRecord::Base 
    has_and_belongs_to_many :categories 
    has_and_belongs_to_many :users 
end 


class Category < ActiveRecord::Base 
    has_and_belongs_to_many :books 
end 

class User < ActiveRecord::Base 
    has_and_belongs_to_many :books 
end 

위의 내용은 내 모델 간의 관계를 선언 한 것입니다. 내 책 컨트롤러 및 양식에서 나는 쉽게 책을 만들어 카테고리와 연관시킬 수 있습니다. 그런데 어떻게 내가 창조 시간에 그 책을 사용자와 연관시킬 수 있을까요? 레일즈 automagic의 일부가 나를 위해이를 처리 할 것인가, 아니면 사용자와 책을 연결시키기 위해 조인 테이블을 업데이트하기 위해 트랜잭션 유형을 수행해야만 할 것인가.레일에서 다중 HABTM 관계

답변

0

당신과 같이 새로운 책을 인스턴스화 할 수 있습니다 :이 @current_user에 책을 스코프

class BooksController < ApplicationController 
    def create 
    @book = @current_user.books.build(params[:book]) 
    ... 
    end 
end 

; @book을 저장하면 @book.user_id@current_user.id으로 설정됩니다. @current_user의 거주 국가는 귀하에게 달려 있습니다.

+0

나는 이것을 시도했다. 그것은 books 테이블, 조인 테이블 (books_categories)에 저장하지만 books_users 테이블에는 항목이 없다. 사용자가 로그인 할 때 저장하는 session_id를 기반으로 @current_user를 채 웁니다. – Dhana

+0

수정 됨 - 올바른 데이터로 저장하려면 @ book.save 대신 @ current_user.save를 호출하십시오. – Dhana