rails collection_select应该打印我的收藏

时间:2016-04-20 11:32:20

标签: ruby-on-rails ruby ruby-on-rails-4

我在尝试使用collection_select时遇到错误;)

我在我的观点中得到了这个代码:

<%= f.collection_select(:channel, :channel_id, @channels, :id, :channelname, prompt: true) %>

在我的控制器中我有这个:

    @channels = Channel.all

我收到了这个错误:

undefined method `merge' for :channelname:Symbol

我的失败是什么?

谢谢!

3 个答案:

答案 0 :(得分:1)

您可以使用

Channel.all.pluck(:id, :channelname)

例如,请看下面的

collection_select(
    :post, # field namespace 
    :author_id, # field name
    # result of these two params will be: <select name="post[author_id]">...

    # then you should specify some collection or array of rows.
    # It can be Author.where(..).order(..) or something like that. 
    # In your example it is:
    Author.all, 

    # then you should specify methods for generating options
    :id, # this is name of method that will be called for every row, result will be set as key
    :name_with_initial, # this is name of method that will be called for every row, result will be set as value

    # as a result, every option will be generated by the following rule: 
    # <option value=#{author.id}>#{author.name_with_initial}</option>
    # 'author' is an element in the collection or array

    :prompt => true # then you can specify some params. You can find them in the docs.
)

答案 1 :(得分:1)

根据文件:

  

collection_select(方法,集合,value_method,text_method,   options = {},html_options = {})public

所以你应该使用:

<%= f.collection_select(:channel_id, Channel.all, :id, :channelname, prompt: true) %>

答案 2 :(得分:0)

试试这个

<%= f.collection_select(:channel_id, :id, prompt: true) %>