never_had_a_name
never_had_a_name

Reputation: 93296

Ruby on rails migration question

In the following code a post is created and belongs to Person:

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

But I wonder which Reading this post belongs to when it's saved.

I dont quite understand that.

Thanks

Upvotes: 0

Views: 52

Answers (1)

Jesse Wolgamott
Jesse Wolgamott

Reputation: 40277

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

Upvotes: 1

Related Questions