开发者

How to access attributes in a partial of a nested rails form?

开发者 https://www.devze.com 2023-02-17 13:54 出处:网络
I want to use the boolean attribute is_white from my inner_object to switch between html code in the the partial _inner_object_form_fields. This is my attempt.

I want to use the boolean attribute is_white from my inner_object to switch between html code in the the partial _inner_object_form_fields. This is my attempt.

<%= form_for @outer_object do |f| %>
  <%= f.fields_for :inner_object do |builder| %>
    <%= render :partial => "inner_object_form_fields", :locals =>  { :f => builder } %>
  <% end %>
<% end %>

This is my attempt of the partial _inner_object_form_fields.

<% if f.is_white == true %>
  <%= f.label(:name, "White") %>
<% else %>
  <%= f.label(:name, "Black") %>
<% end %>

This is the migration file of InnerObj开发者_开发问答ects.

class InnerObjects < ActiveRecord::Migration
  def self.up
    create_table :inner_objects do |t|
      t.string "name"
      t.boolean "is_white", :default => true
      t.timestamps
    end
  end
  def self.down
    drop_table :inner_objects
  end
end

I found a similar question but could not retrieve an answer for me. The question is: How can access the attribut is_white? My example does NOT work.


Try

<% if f.object.is_white == true %>

Seem to remember you could access the object this way (not 100% sure though ;)


Is it because f.is_white is based on a blank object in the partial? Try

<%= form_for @outer_object do |f| %>
 <%= f.fields_for f.inner_object do |builder| %>
   <%= render :partial => "inner_object_form_fields", :locals =>  { :f => builder } %>
 <% end %>
<% end %>

That way it's referencing the attached object and any state you've created.


Even one step further would be to do something like this:

 <%= f.fields_for f.inner_object do |builder| %>
   <%= render :partial => "inner_object_form_fields", :locals =>  { :f => builder, :inner_object => builder.object } %>
 <% end %>

Then you can do.

<% if inner_object.is_white == true %>

This way your partials code looks a little cleaner.

0

精彩评论

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