Ruby-on-rails Rails form_for 和 collection_select

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

Rails form_for with collection_select

ruby-on-railsruby-on-rails-3

提问by Rymo4

I'm trying to create a field that creates an instance of the Ranking class. It has a comment field already which sets the params[:ranking][:comment]but now I want to add a drop down that displays something like:

我正在尝试创建一个字段来创建 Ranking 类的实例。它已经有一个注释字段,用于设置params[:ranking][:comment]但现在我想添加一个下拉菜单,显示如下内容:

1: horrible, 2: poor, 3: mediocre, 4: good, 5: great

1:可怕,2:差,3:一般,4:好,5:很棒

I would like these to set the params[:ranking][:score] to a value 1-5 so that in my create method I can do something like this:

我希望这些将 params[:ranking][:score] 设置为值 1-5,以便在我的 create 方法中我可以执行以下操作:

 @ranking = Ranking.new( #....
                        :score => params[:ranking][:score])

My form looks like this right now:

我的表格现在看起来像这样:

<%= form_for([@essay, @ranking]) do |f| %>
  <%= render 'shared/error_messages', :object => f.object %>
  <div classs="field">
    <%= f.text_area :comment %>
  </div>
  <div classs="field">
      <%= #something here!%>
  </div>
  <div class="actions">
    <%= f.submit "Submit" %>
  </div>
<% end %>

I know that I need to use the collection_selectbut I haven't been able to get it working.

我知道我需要使用 ,collection_select但我一直无法让它工作。

回答by Aaron Hinni

You should just be able to use the regular selecthelper for something like that:

您应该能够将常规select助手用于类似的事情:

f.select :score, [['horrible', 1], ['poor', 2], ['mediocre', 3], ['good', 4], ['great', 5]]

You would use collection_selectif you had a model for the scores. Something like:

collection_select如果您有分数模型,您将使用。就像是:

f.collection_select :score_id, Score.all, :id, :name

See the API docs for collection_select

请参阅collection_select的 API 文档