Using Rails 2.3.8
Goal is to create a Blogger while simultaneously updating the nested User model (in case info has changed, etc.),
I'm using Rails 3.2.8 and running into the exact same problem.
It appears that what you are trying to do (assign/update an existing saved record to a belongs_to
association (user
) of a new unsaved parent model (Blogger
) is simply not possible in Rails 3.2.8 (or Rails 2.3.8, for that matter, though I hope you've upgraded to 3.x by now)... not without some workarounds.
I found 2 workarounds that appear to work (in Rails 3.2.8). To understand why they work, you should first understand the code where it was raising the error.
In my version of activerecord (3.2.8), the code that handles assigning nested attributes for a belongs_to
association can be found in lib/active_record/nested_attributes.rb:332
and looks like this:
def assign_nested_attributes_for_one_to_one_association(association_name, attributes, assignment_opts = {})
options = self.nested_attributes_options[association_name]
attributes = attributes.with_indifferent_access
if (options[:update_only] || !attributes['id'].blank?) && (record = send(association_name)) &&
(options[:update_only] || record.id.to_s == attributes['id'].to_s)
assign_to_or_mark_for_destruction(record, attributes, options[:allow_destroy], assignment_opts) unless call_reject_if(association_name, attributes)
elsif attributes['id'].present? && !assignment_opts[:without_protection]
raise_nested_attributes_record_not_found(association_name, attributes['id'])
elsif !reject_new_record?(association_name, attributes)
method = "build_#{association_name}"
if respond_to?(method)
send(method, attributes.except(*unassignable_keys(assignment_opts)), assignment_opts)
else
raise ArgumentError, "Cannot build association #{association_name}. Are you trying to build a polymorphic one-to-one association?"
end
end
end
In the if
statement, if it sees that you passed a user ID (!attributes['id'].blank?
), it tries to get the existing user
record from the blogger's user
association (record = send(association_name)
where association_name is :user
).
But since this is a newly built Blogger
object, blogger.user is going to initially be nil
, so it won't get to the assign_to_or_mark_for_destruction
call in that branch that handles updating the existing record
. This is what we need to work around (see the next section).
So it moves on to the 1st else if
branch, which again checks if a user ID is present (attributes['id'].present?
). It is present, so it checks the next condition, which is !assignment_opts[:without_protection]
.
Since you are initializing your new Blogger object with Blogger.new(params[:blogger])
(that is, without passing as: :role
or without_protection: true
), it uses the default assignment_opts
of {}
. !{}[:without_protection]
is true, so it proceeds to raise_nested_attributes_record_not_found
, which is the error that you saw.
Finally, if neither of the other 2 if branches were taken, it checks if it should reject the new record and (if not) proceeds to build a new record. This is the path it follows in the "create a brand new user if it doesn't exist yet" case you mentioned.
without_protection: true
The first workaround I thought of -- but wouldn't recommend -- was be to assign the attributes to the Blogger object using without_protection: true
(Rails 3.2.8).
Blogger.new(params[:blogger], without_protection: true)
This way it skips the 1st elsif
and goes to the last elsif
, which builds up a new user with all the attributes from the params, including :id
. Actually, I don't know if that will cause it to update the existing user record like you were wanting (probably not—haven't really tested that option much), but at least it avoids the error... :)
self.user
in user_attributes=
But the workaround that I would recommend more than that is to actually initialize/set the user
association from the :id param so that the first if
branch is used and it updates the existing record in memory like you want...
accepts_nested_attributes_for :user
def user_attributes=(attributes)
if attributes['id'].present?
self.user = User.find(attributes['id'])
end
super
end
In order to be able to override the nested attributes accessor like that and call super
, you'll need to either be using edge Rails or include the monkey patch that I posted at https://github.com/rails/rails/pull/2945. Alternatively, you can just call assign_nested_attributes_for_one_to_one_association(:user, attributes)
directly from your user_attributes=
setter instead of calling super
.
In my case, I ended up deciding that I didn't want people to be able to update existing user records from this form, so I ended up using a slight variation of the workaround above:
accepts_nested_attributes_for :user
def user_attributes=(attributes)
if user.nil? && attributes['id'].present?
attributes.delete('id')
end
super
end
This approach also prevents the error from occurring, but does so a little differently.
If an id is passed in the params, instead of using it to initialize the user
association, I just delete the passed-in id so that it will fall back to building a new
user from the rest of the submitted user params.
Try adding a hidden field for the user's id in the nested form:
<%=user_form.hidden_field :id%>
The nested save will use this to determine if it is a create or an update for the User.
I ran into the same error in rails 3.2. The error occurred when using a nested form to create a new object with a belongs to relationship for an existing object. Tyler Rick's approach did not work for me. What I found to work was to set the relationship following the initialization of the object and then setting the objects attributes. An example of this is as follows ...
@report = Report.new()
@report.user = current_user
@report.attributes = params[:report]
assuming params looks something like ... {:report => { :name => "name", :user_attributes => {:id => 1, { :things_attributes => { "1" => {:name => "thing name" }}}}}}