Howto: Access a second related model in a nested attribute builder block

Posted by Joe Cairns on Stack Overflow See other posts from Stack Overflow or by Joe Cairns
Published on 2010-05-15T17:05:04Z Indexed on 2010/05/15 17:14 UTC
Read the original article Hit count: 223

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 %>

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about nested-attributes