Ruby-on-rails Rails 表单(选择/选项)-如何使用 HAML 标记选定的选项?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12691309/
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 20:48:50  来源:igfitidea点击:

Rails form (select/option) - how to mark selected option with HAML?

ruby-on-railsformsselecthamloption

提问by user984621

What's the quickest and most elegant way to mark currently selected option value in the form in HAML?

在 HAML 的表单中标记当前选择的选项值的最快和最优雅的方法是什么?

%form{:action => '', :method => 'get'}
   %select{:name => 'param_name'}
      %option{:value => 'A'} A data
      %option{:value => 'B'} B data

One way:

单程:

- if params[:param_name] == "A"
  %option{:value => 'A', :selected => 'selected'} A data
- else
  %option{:value => 'A'} A data

but this is inappropriate when the selectbox will has many option fields...

但是当select框有很多选项字段时这是不合适的......

回答by egze

Something like this will work (using the older "hashrocket syntax" with the operator =>)

像这样的东西会起作用(将旧的“hashrocket 语法”与操作符一起使用=>

%select
  %option{:value => "a", :selected => params[:x] == "a"}= "a"
  %option{:value => "b", :selected => params[:x] == "b"}= "b"

Or, in newer Ruby versions (1.9 and greater):

或者,在较新的 Ruby 版本(1.9 及更高版本)中:

%select
  %option{value: "a", selected: params[:x] == "a"}= "a"
  %option{value: "b", selected: params[:x] == "b"}= "b"

回答by Mik

You should unleash the power of rails helpers.

你应该释放 rails helpers 的力量。

For selecttag:

对于select标签

= select_tag :param_name, options_for_select([['A data', 'A'], ['B data', 'B']], params[:param_name])

Also, instead of raw %formuse form_tagor better form_forwhen it's possible (or more better simple_form or formtastic)

此外,在可能的情况下,不要%form使用原始使用form_tag或更好form_for(或更好的 simple_form 或 formtastic)