burner1up
burner1up

Reputation: 61

why is my form not generating select options?

I'm trying to build a simple filter on my raffles index page to filter my raffles by category. However, none of the select options are populating- the drop down is completely blank. I think it's something to do with my view, I'm admittedly no expert with forms.

#app/controllers/raffles_controller.rb 
def index
  @raffles = Raffle.filter(params[:filter])
end

#app/models/raffle.rb
class Raffle < ApplicationRecord
has_many :tickets
has_many :users, through: :tickets

  def self.filter(filter)
    if filter
        raffle = Raffle.where(category: filter)
    else
        Raffle.all
    end
  end

end

#app/views/raffles/index.rb
<h1>Current Raffles:</h1>
  <%= form_tag(raffles_path, method: 'get') do %>
    <%= select_tag(Raffle.pluck(:category).uniq, params[:filter]) %>
    <%= submit_tag ("Filter") %>
  <% end %>

any ideas?

Upvotes: 0

Views: 36

Answers (1)

Jos&#233; Coelho
Jos&#233; Coelho

Reputation: 526

Your call to select_tag is missing the name on the first parameter, and your list of options should be built as well.

To build the property list you can use the helper options_for_select

If you want to define a selected value, you can send it to options_for_select as well.

Based on your example, this should do the job:

<%= select_tag(:filter, options_for_select(Raffle.pluck(:category).uniq, params[:filter])) %>

A good source when you have questions about how a certain form helper works are https://guides.rubyonrails.org/form_helpers.html#the-select-and-option-tags

Upvotes: 2

Related Questions