Search code examples
ruby-on-railsruby-on-rails-4fields-for

Referencing attributes within a fields_for do block


I have a bit of an odd application where I need to reference the current values of the attributes being loaded by fields_for. The application takes a bit of explanation (it's to cater to a somewhat quirky but necessary jquery plugin) so I'll describe it with a simpler example.

Say I'm loading a list of customers into a form . And (for some reason) I want to head each person's fields with the name currently saved to the database before providing the fields to change it. Something like this:

<%= company.simple_fields_for :customers do |customer|%>
  <span>Name previously saved was: <%= customer.name %></span>
  <%= customer.input :name %>
<% end %>

Obviously the <%= customer.name %> above isn't a legitimate use for the builder but how might I reference the name attribute of each customer? Again, please pardon the goofy example.

Many thanks in advance.


Solution

  • I believe you should be able to access the customer object via customer.object, in the same way you can access the root object via form.object:

    <%= company.simple_fields_for :customers do |customer|%>
      <span>Name previously saved was: <%= customer.object.name %></span>
      <%= customer.input :name %>
    <% end %>