2010-07-31 3 views
0

에 게시물이 사람에 작성 속한다 :루비는 다음 코드에서 레일 마이그레이션 질문

class Person < ActiveRecord::Base 
    has_many :readings 
    has_many :posts, :through => :readings 
end 

person = Person.create(:name => 'john') 
post = Post.create(:name => 'a1') 
person.posts << post 

하지만이 글을 읽는 것은 그것을 저장할 때에 속한 궁금하다.

나는 그것을 아주 잘 모른다.

감사

답변

1

이제

, 내가 만약 당신이 원하는 생각하지 않는다, 그래서 당신은 아마 저장 그 존재에 대해 보호 할 것입니다 전무 post.reading은 다음과 같습니다

class Reading < ActiveRecord::Base 
    belongs_to :person 
    has_many :posts 
    validates_presence_of :person 
end 

하지만 여전히 나에게 조금 틀린 것처럼 보입니다. 나는 독자적으로 Person을 가질 수 있다고 생각할 것이고, 독자적으로 Post를 가질 수 있다고 생각합니다. 그러나 독서는 Person과 Post의 교차점입니다. 이 경우 :

class Person 
    has_many :readings 
end 

class Post 
    has_many :readings 
end 

class Reading 
    belongs_to :person 
    belongs_to :post 
    validates_presence_of :person, :post 
end