views:

51

answers:

1

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 %>
+1  A: 

The answer was found in analyzing how the rails FormBuilder works. So in the example above where I need to access the actual wtf object so I can get a property on bar, I need to do the following:

 <h2>Bars</h2>
  <% f.fields_for :wtfs do |builder| %>
    <%= builder.hidden_field :bar_id %>
    <p>
     <%= builder.label builder.object.bar.data_i_need_for_a_label %>
     <%= builder.text_field :wtf_data_i_need_to_set %>
    </p>
  <% end %>
Joe Cairns