Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fields_for with nested attribute, has_many through association

I have 3 models - standards, layers, and layers_assocs. Standards has many layers through layer_assocs and the rest is trivial. The layers_assocs table stores the standards_id, layer_id and a visible boolean while the layers table is just a look up table with name (and auto-increment id).

On the standards options page, I have a check box which updates the :visible nested attribute. I'm looking for a way to show the associated layer name in a form label. Currently, I have this for the check box:

<%= f.fields_for :layers_assocs do |assoc| %>
  <%= assoc.check_box :visible %>
<% end %>

How I would display the associated layer name with the layers_assocs belongs_to layers association is a mystery. I can display layer_id with this

<%= assoc.text_field :layer_id %>

But trying to use that as an integer for displaying name through layers like standard.layers[assoc.layer_id] or standard.layers[:layer_id] doesn't fly. assoc is a FormBuilder object so I'm not sure what to do. Inspecting assoc spits out a huge object with everything in the standard.

I've checked the rails api on fields_for and this question with no luck. Either :name or :visible is undefined.

like image 768
Archonic Avatar asked Oct 22 '25 05:10

Archonic


1 Answers

Got it. Must have been the coffee.

<% @standard.layers_assocs.each do |assoc| %>
  <%= f.fields_for :layers_assocs, assoc do |layer_field| %>
    <%= layer_field.label assoc.layer.name %>
    <%= layer_field.check_box :visible %>
  <% end %>
<% end %>

For the check box to work, it needs the visible attribute as a key. f.check_box layer_assoc.visible will just think you're trying to force feed it 'true' or 'false'. The issue with getting the name then is that when :visible is in the right scope, layer_assoc.layer.name isn't accessible within the fields_for block because layer_field is a FormBuilder object, not a layers_assoc object. The above makes sure both scopes are available and the output isn't overdone. f.fields_for :layers_assoc would output as many duplicates as there are objects in the standards layer_assocs array. f.fields_for :layers_assoc, assoc limits it to the correct amount.

Note that the form label isn't properly "attached" with for="..." in the output HTML to it's associated check box. I can deal with it but let me know if you know a better way.

like image 162
Archonic Avatar answered Oct 23 '25 22:10

Archonic