开发者

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜