Creating a simple drop-down menu in Rails

和自甴很熟 提交于 2019-12-05 09:14:09

问题


This really seems simple enough yet for some reason I'm missing something critical.

I have a view:

<% form_for :foo, @foo, :url => {:action => 'bar'} do |f|%> 
  <%= f.collection_select :range, FooModel::MONTHS%>
  <%= submit_tag "Submit", :disable_with => "Submitting..." %>
<% end %>

I have a model:

class FooModel < ActiveRecord::Base
  MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep']
end

And I have a controller:

def new
  @foo = FooModel.new
end

def index
  respond_to do |format|
    format.html # index.html.erb
  end
end

def bar
  if params[:foo]
    @foos = params[:foo].inspect
  end

  respond_to do |format|
    format.html # index.html.erb
  end
end

My question is, how do I get at the information as to which combo box element had been selected when the Submit button was clicked? It doesn't seem to be params[:foo], @foo, or anything else I can think of.

Update Looking at it it seems like I should maybe be calling params[:range]? That, however, is nil.


回答1:


I think your code can be simplified to work this way:

<% form_for @foo, :url => {:action => 'bar'} do |f| %>
  <%= f.select :range, FooModel::MONTHS %>
  <%= submit_tag "Submit", :disable_with => "Submitting..." %>
<% end %>

Using collection_select for simple cases such as this one is probably overkill. f.select should be sufficient.



来源:https://stackoverflow.com/questions/4856201/creating-a-simple-drop-down-menu-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!