class User < ActiveRecord::Base
has_many :boxes
has_many :books
end
class Box < ActiveRecord::Base
belong_to :user
has_many :books
end
class Book < ActiveRecord::Base
belongs_to :user
belongs_to :box
end
So when I run below in a console it works as I expect, creating a new box and attaching the user_id to the box
>> u = User.first
>> u.boxes.build(:height => 3, :width => 1, :length => 4)
>> u.save
So then I go further and attempt this. The box_id is set, but the user_id in books is not set.
>> u.boxes.first.books.build(:title => 'Reading is fun')
>> u.save
It seems like I’m missing a pretty fundamental concept here.
Each relationship is distinct from all the others. That is, when you
builda Book belonging tou.boxes.first, all Rails infers is that the Book belongs to that Box; it says nothing about the User.In this situation, where (presumably) Books are always owned by the person who owns the Box they’re in, you’re probably best off with a
has_many :throughrelationship:If that’s not the case (perhaps you’re helping me move?), leave the associations as they are, but you’ll have to set at least one of the relations up manually, for instance:
(Couple of other points. In your second example you should save the Book, not the User; and you can do both
buildandsavein a single operation withcreate)