Ruby-on-rails Rails 选择标记选定值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15252900/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 21:34:07  来源:igfitidea点击:

Rails select tag selected value

ruby-on-railsruby-on-rails-3ruby-on-rails-3.1

提问by Yogzzz

My tag:

我的标签:

<%= select_tag(:option, options_for_select([['All', 1], ['Co', 2], ['Bought', 3], ['View', 4], ['Top API', 5], :selected => :option ])) %>

How do I set the selected value to which option is selected. For example, if I select ['Bought', 3], and submit, ['All', 1]option is selected. How can I display the selected value after the form is submitted.

如何将选定的值设置为选择的选项。例如,如果我选择['Bought', 3]并提交,['All', 1]则选择了选项。提交表单后如何显示选定的值。

回答by gabrielhilal

You did everything right, just close the options ]before the :selected => :option:

你做的一切都对,只需关闭]之前的选项:selected => :option

instead of ...], selected: :option ])), change to ...]], selected: :option ))

而不是...], selected: :option ])),改为...]], selected: :option ))

So, your code should be:

所以,你的代码应该是:

<%= select_tag(:option, options_for_select([['All', 1], ['Co', 2], ['Bought', 3], ['View', 4], ['Top API', 5]], selected: :option )) %>

回答by Jonathan MacDonald

Try this:

尝试这个:

<%= select_tag(:option, options_for_select([['All', 1], ['Co', 2], ['Bought', 3], ['View', 4], ['Top API', 5]], :selected => params[:option])) %>

This works perfectly in rails 4.2

这在 rails 4.2 中完美运行

回答by Gabriel Lucuy

In case you want to add a class to the tag:

如果您想向标签添加一个类:

<%= select_tag(:option, options_for_select([["Option 1",1],["Option 2",2],["Option 3",3]], params[:option] ), class:"select") %>

Worrking in rails 5.

5. 在轨道上工作