2

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 InnerObjects.

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.

3 Answers 3

5

Try

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

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

0
0

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.

1
  • 1
    Sorry Anthony. This does not work for me. I edit my post for clearance.
    – JJD
    Mar 18, 2011 at 21:05
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.