I have the following code for creating pictures for users in my users controller:
def new
@user = User.new
@pictures = @user.pictures.build({:placement => "front"},{:placement => "profile"})
end
However, when I create a new user, it isn't automatically building pictures with placement "front" or "profile." In fact, there's no update whatsoever to pictures. The pictures model has
attr_accessible :placement
and in picture.rb
belongs_to :user
and in user.rb
has_many :pictures
accepts_nested_attributes_for :pictures, allow_destroy: true
Why is my build command silently failing?
UPDATE
Using .save!, I have learned that @pictures
are being assigned, but the problem is no user_id being associated with them. When I intentionally assign the user_id, as in:
def new
@user = User.new
@pictures = @user.pictures.build({:placement => "front", :user_id => @user.id},{:placement => "profile", :user_id => @user.id})
end
It still does not assign a user_id.
Strangely, when I run the very same commands in the rails console, it does correctly assign the user_id.
It appears that the new @user does not get an auto id assigned to him until after the @pictures command is run, yet the console version is succeeding because it is performing the operations in sequence.
So, that's why I'm seeing a blank id.
Why is this happening? And isn't this simultaneous id assignment something the model is supposed to take care of with belongs_to
and has_many
, and accepts_nested_attributes_for
?
What is the appropriate way to address assigning nested attributes if the ID that links them together isn't created until after save?
Why does this not work?
Not sure if this is your problem, but you need to add :user_id to your attr_acessible line in picture.rb. Any attributes you want to read/write need to be attr_accessible or you will get that mass-assignment error.
It's in the docs: the user-ID is assigned by the database, after it is saved. So you have to save the user first, before you can use the user_id.
If you change :user_id => @user.id to :user => @user it should work, because then Rails is able to save them in the proper order, it knows it is not saved yet and needs to update those relations.