Lee McAlilly
Lee McAlilly

Reputation: 9316

How to use a Rails collection select inside a block

I'm using Simple Form in my Rails 6 e-commerce inventory tracking, and I need to have multiple collection selects in my form that appear based on an association.

Here's the data model:

Product
   has_many Option(s)
Option
   has_many Choice(s)
   belongs_to Product
Choice
   has_many Variant(s)
   belongs_to Option
Variant
   belongs_to Choice(s)

So a Product might look like this:

Product => T-Shirt
Options => Size { choices: small, medium, large }, Color { choices: red, green, blue }
Variant #1 => T-Shirt in Medium Red, etc.

How do I build the collection selects for the Product Options when not every product will have the same number of options that the customer will need to choose such as size or color? Some products might have 0 options, others 1 (e.g. just color), 2 (e.g. size and color), 3, etc.

So, on the Variant form I'd like to gather the collections that belong to the associated product. I can show them on the Variant#show view like this:

<ul>
  <% @product.options.each do |option| %>
    <li>
      <%= option.name %>
      <ul>
        <% option.choices.each do |choice| %>
          <li><%= choice.name %></li>
        <% end %>
      </ul>
    </li>
  <% end %>
</ul>

That works as expected in the Variants#show view.

But how do you do this same sort of thing and gather 0 or more Options with their associated choices in the Variant form with a collection_select? I'm using simple form, so I'm trying something like this, but it's not working and I'm blocked:

<% @variant.product.options.each do |option| %>
    <div class='form-row'>
      <div class='col'>
        <%= f.label option.name %>
        <% option.choices.each do |choice| %>
          <%= f.association choice %>
        <% end %>
      </div><!-- /.col -->
    </div><!-- /.form-row -->
  <% end %>

That version of the form gives me the following error:

RuntimeError in Variants#edit

enter image description here

Upvotes: 4

Views: 352

Answers (0)

Related Questions