开发者

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

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 %>
    &开发者_如何学运维lt;/p>
  <% end %>

  <p>
    <%= f.submit 'Create' %>
  </p>
<% end %>

<%= link_to 'Back', foos_path %>


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜