I’ve got a simple nested form working in my rails3 application. I’m trying to work out how to save a value from the parent model into the child when saving.
class Radcheck < ActiveRecord::Base
set_table_name 'radcheck'
attr_accessible :attribute_name, :username, :value, :op
belongs_to :raduser
end
class Raduser < ActiveRecord::Base
has_many :radcheck, :dependent => :destroy
accepts_nested_attributes_for :radcheck
end
And my form:
<%= form_for @raduser do |f| %>
<p>
<%= f.label :username %><br />
<%= f.text_field :username %>
</p>
<%= f.fields_for :radcheck do |builder| %>
<li>
<%= builder.label :attribute_name %><%= builder.text_field :attribute_name %>
</li>
<% end %>
<p><%= f.submit "Submit" %></p>
<% end %>
What I want to do is save the Raduser.username value in to the radcheck table on save. For each record.
I’ve tried putting something in the controller but that wasn’t really working for us.
— Update —
In my radcheck controller, I’ve tried this (as a test) but the values don’t save.
def create
@radcheck = Radcheck.new(params[:radcheck])
@radcheck.username = '123'
respond_to do |format|
if @radcheck.save
format.html { redirect_to @radcheck, notice: 'Radcheck was successfully created.' }
format.json { render json: @radcheck, status: :created, radcheck: @radcheck }
else
format.html { render action: "new" }
format.json { render json: @radcheck.errors, status: :unprocessable_entity }
end
end
end
Have also tried in radusers but that gave error.
It looks like the controller code you posted is for the Radcheck controller, correct? If so, the form you have also posted will be using the
createaction of theRaduserControllerclass, not the one fromRadcheckController. This would explain why you aren’t seeing the username ‘123’ in the radcheck rows.If the username field is the same between parent and child, a common way to sync these two up would be with an observer or a
before_savecallback. I’ll outline thebefore_savemethod below:I’ve tested this with Rails 3.1 and it works; however, I know I have run into issues accessing parent models within a child model in previous versions of Rails. In those cases, I had to put the
before_saveaction on the parent model, and have it iterate over each child, setting the appropriate attributes that way.