Howto: Access a second related model in a nested attribute builder block
- by Joe Cairns
I have a basic has_many through relationship:
class Foo < ActiveRecord::Base
has_many :bars, :dependent => :destroy
has_many :wtfs :through => :bars
accepts_nested_attributes_for :bars, :wtfs
end
On my crud forms I have a builder block for the wtf, but I need the label to come from the bar (an attribute called label for instance). What's the proper method to do this?
Here's the most simple scaffold:
<h1>New foo</h1>
<% form_for(@foo) do |f| %>
<%= f.error_messages %>
<p>
<%= f.label :name %><br />
<%= f.text_field :name %>
</p>
<h2>Bars</h2>
<% f.fields_for :wtfs do |builder| %>
<%= builder.hidden_field :bar_id %>
<p>
<%= builder.text_field :wtf_data_i_need_to_set %>
</p>
<% end %>
<p>
<%= f.submit 'Create' %>
</p>
<% end %>
<%= link_to 'Back', foos_path %>