【问题标题】:why is my form not generating select options?为什么我的表单不生成选择选项?
【发布时间】:2020-10-04 20:51:49
【问题描述】:

我正在尝试在我的抽奖索引页面上构建一个简单的过滤器来按类别过滤我的抽奖。但是,没有任何选择选项被填充 - 下拉列表完全空白。我认为这与我的观点有关,我承认我不是表格专家。

#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 %>

有什么想法吗?

【问题讨论】:

    标签: ruby-on-rails ruby forms


    【解决方案1】:

    您对select_tag 的调用缺少第一个参数上的名称,您的选项列表也应该建立。

    要构建属性列表,您可以使用帮助器options_for_select

    如果你想定义一个选定的值,你也可以将它发送到options_for_select

    根据您的示例,这应该可以完成工作:

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

    当您对某个表单助手的工作方式有疑问时,一个很好的来源是https://guides.rubyonrails.org/form_helpers.html#the-select-and-option-tags

    【讨论】:

      猜你喜欢
      • 2013-01-01
      • 2017-09-04
      • 1970-01-01
      • 1970-01-01
      • 2020-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-12
      相关资源
      最近更新 更多