Ruby on rails migration question
In the following code a post is created and belongs to Person:
class开发者_如何学Go 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
But I wonder which Reading this post belongs to when it's saved.
I dont quite understand that.
Thanks
post.reading would be nil
Now, I don't think that's what you want, so you'd probably want to protect against that beings saved:
class Reading < ActiveRecord::Base
belongs_to :person
has_many :posts
validates_presence_of :person
end
But, that still seems a bit wrong to me... I'd think that you could have a Person on its own, and a Post on its own, but a reading is the intersection of a Person and a Post. In that case:
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
精彩评论