Mel
Mel

Reputation: 2683

Rails 4 - Simple Form collection by scope

I am trying to make an app in Rails 4.

I use simple form for forms.

I have an industry model.

The industry.rb has:

scope :alphabetically, -> {  order("sector ASC") }

The industry controller has:

def index
    #@industries = Industry.all
    @industries = Industry.alphabetically
  end

The industry form has:

<%= simple_form_for(@industry) do |f| %>
            <%= f.error_notification %>

                <div class="form-inputs">


                    <%= f.select :sector, options_from_collection_for_select(Industry.alphabetical), :prompt => 'Select' %>  

                    <%= f.input :icon, as: :file, :label => "Add an icon" %>

                </div>

                <div class="form-actions">
                    <%= f.button :submit, "Submit", :class => 'formsubmit' %>
                </div>
        <% end %>

I'm trying to get my form input for :sector to use the collection of industries (by calling the scope).

When I try this, I get the following error:

undefined method `alphabetical' for #<Class:0x007fef65635220>

Can anyone see what's wrong?

Upvotes: 1

Views: 495

Answers (1)

K M Rakibul Islam
K M Rakibul Islam

Reputation: 34338

It should be alphabetically instead of alphabetical. Also, according to the options_from_collection_for_select documentation, you need to pass at least 3 arguments to the options_from_collection_for_select method: collection, value_method and text_method.

Change to the following to make it work:

<%= f.select :sector, options_from_collection_for_select(Industry.alphabetically, 'id', 'sector'), :prompt => 'Select' %>

Upvotes: 1

Related Questions