Friday, October 28, 2011

accepts_nested_attributes_for, belongs_to, and has_many#build

There's a self-explainatory code sample before.

Basically, if you have accepts_nested_attributes_for on a belongs_to relation, you can't use model.has_many_relationship.build params[:has_many_relationship] -- Rails bugs out.

This is because, AFAIK, model.has_many_relationship.build params[:has_many_relationship]

assigns params[:has_many_relationship] first, BEFORE assigning the foreign keys that link the relationship with the model.

Code:


class User < ActiveRecord::Base
has_many :papers
end

class Paper < ActiveRecord::Base
belongs_to :user
accepts_nested_attributes_for :user
end



class PagesController
def create
# The below line FAILS;
# current_user.papers.build params[:paper]
paper = current_user.papers.build
paper.attribute
end
end


"current_user.papers.build params[:paper]" does this under the hood:

# this triggers accepts_nested_attributes_for, when user_id is currently blank, so it will fail.
Paper.new params[:paper]
Paper.user_id = current_user.id # too little, too late!

No comments: