简体   繁体   English

下拉列表未显示rails

[英]Dropdown list not showing rails

I have a dropdown list that is supposed to show all the users in the db. 我有一个下拉列表,应该显示数据库中的所有用户。 The dropdown is showing but the contents of the dropdown are not. 下拉列表正在显示,但下拉列表的内容不是。

当我说下拉内容没有显示时,这就是我的意思

I'm getting the content from the MessagesHelper which is: 我从MessagesHelper获取的内容是:

module MessagesHelper
 def recipients_options(chosen_recipient = nil)
   s = ''
   User.all.each do |user|
    s << "<option value='#{user.id}' #{'selected' if user == chosen_recipient}>#{user.username}</option>"
   end

   s.html_safe
  end
end

And I render it using this code: 我使用此代码渲染它:

<%= select_tag 'recipients', recipients_options(@chosen_recipient), class: 'form-control chosen-it' %>

Anyone seeing what I'm missing out on? 有人看到我错过的东西吗? I'll really appreciate the help. 我真的很感激帮助。

You should really be using options_from_collection_for_select for this. 你应该真的使用options_from_collection_for_select

This, to quote the docs: 这,引用文档:

Returns a string of option tags that have been compiled by iterating over the collection and assigning the result of a call to the value_method as the option value and the text_method as the option text. 返回一个选项标记字符串,这些选项标记是通过迭代集合并将调用结果分配给value_method作为选项值并将text_method作为选项文本分配而编译的。

That way, you can simply use: 这样,你可以简单地使用:

<%= select_tag 'recipients', options_from_collection_for_select(User.all, :id, :username, @chosen_recipient.id), class: 'form-control chosen-it' %>

This is a built in helper designed to do what you're recreating, so will work perfectly. 这是一个内置的帮助器,旨在完成您正在重新创建的内容,因此可以完美地工作。

The arguments are the collection to build options from, the method to call for the value, the method for the options' text and the selected value. 参数是用于构建选项的集合,调用值的方法,选项文本的方法和选定的值。

Hope that helps - let me know how you get on or if you have any questions. 希望有所帮助 - 让我知道你是如何得到的,或者如果你有任何问题。

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

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