Ruby-on-rails Rails 中的下拉框

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

Drop down box in Rails

ruby-on-rails

提问by alamodey

How do I use Rails to create a drop-down selection box? Say if I have done the query:

如何使用 Rails 创建下拉选择框?说我是否已经完成了查询:

@roles = Role.all

Then how do I display a box with all the @roles.name's ?

那么如何显示一个包含所有@roles.name 的框?

EDIT:After implementing the dropdown box. How do I make it respond to selections? Should I make a form?

编辑:实现下拉框后。我如何让它响应选择?我应该制作表格吗?

回答by David Burrows

use the collection_select helper http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#M001593

使用 collection_select 助手 http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#M001593

This will allow you to write something like:

这将允许您编写如下内容:

collection_select(:user, :role_id, @roles, :id, :role_title, {:prompt => true})

And get

并得到

<select name="user[role_id]">
  <option value="">Please select</option>
  <option value="1" selected="selected">Administrator</option>
  <option value="2">User</option>
  <option value="3">Editor</option>
</select>

回答by erik

This will create a drop down that displays the role name in the drop down, but uses the role_id as the value passed in the form.

这将创建一个下拉列表,在下拉列表中显示角色名称,但使用 role_id 作为表单中传递的值。

select("person", "role_id", @roles.collect {|r| [ r.name, r.id ] }, { :include_blank => true })

回答by Jamie Rumbelow

The form helper has a group of methods specifically written to create dropdown select boxes. Usually you'll use the select_tagmethod to create dropdown boxes, but in your case you can use collection_select, which takes an ActiveRecord model and automatically populates the form from that. In your view:

表单助手有一组专门用于创建下拉选择框的方法。通常,您将使用select_tag方法创建下拉框,但在您的情况下,您可以使用 collection_select,它采用 ActiveRecord 模型并自动从中填充表单。在您看来:

<%= collection_select @roles %>

Find out more about the Rails form helper here: http://guides.rubyonrails.org/form_helpers.html

在此处了解有关 Rails 表单助手的更多信息:http: //guides.rubyonrails.org/form_helpers.html

回答by V-SHY

Display role name as comboBox showing text (1st pluck argument) and it represents the role id

将角色名称显示为显示文本的组合框(第一个 pluck 参数),它代表角色 ID

Controller

控制器

@roles = Role.pluck(:name, :id)

View

看法

<%= select("role", "role_id", @roles) %>

params[:role][:role_id]passed to controller from view.

params[:role][:role_id]从视图传递给控制器​​。