简体   繁体   English

如何将select标签与Rails中控制器中的数组一起使用?

[英]How do I use the select tag with an array made in the controller in Rails?

I have made an array in my controller of a certain model. 我在某个模型的控制器中制作了一个数组。 I stored that array in the variable @students. 我将该数组存储在变量@students中。 I am having trouble getting it to fill out a select dropdown. 我无法填写选择下拉列表。

My current code is: 我目前的代码是:

= select :student_name, :id, @students

I want to be able to list the students by their name, which could be called at student.name and I want to be the value of each to be set as student. 我希望能够按照他们的名字列出学生,这可以在student.name上调用,我希望将每个学生的价值设置为学生。

Any help would be great, as I am a beginner with rails. 任何帮助都会很棒,因为我是rails的初学者。 By the way, I am using Rails 4 顺便说一下,我正在使用Rails 4

You can use options_from_collection_for_select 您可以使用options_from_collection_for_select

Try to get all the students name and id in active-record no need to assign in array. 尝试获取活动记录中的所有学生姓名和ID,无需在数组中分配。

<% options = options_from_collection_for_select(@students, 'id', 'name') %>
<%= f.select :all_val,  options %>

And if you really wants to do in array then do that following way. 如果你真的想在数组中做,那么按照以下方式做。

 @students = [["john", 1], ["mandos", 2], ["kendy", 3]]
    <% options = options_from_collection_for_select(@students, 'id', 'name') %>
    <%= f.select :all_val,  options %>

AS @Bharat soni Suggested,using option-from_collection_for_select would be great! AS @Bharat soni建议,使用option-from_collection_for_select会很棒! Although if you don't want it,you can simply list those options in select tag itself like this 虽然如果你不想要它,你可以简单地在select标签中列出这些选项

= select :student_name,@students,'id','name' #Would give the list of student names in the dropdown

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM