【问题标题】:rails collection_select should print my collectionrails collection_select 应该打印我的收藏
【发布时间】:2016-04-20 11:32:19
【问题描述】:

我在尝试使用 collection_select 时出错;)

我在我看来得到了这段代码:

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

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

    @channels = Channel.all

我得到了这个错误:

undefined method `merge' for :channelname:Symbol

我的失败是什么?

非常感谢!

【问题讨论】:

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


【解决方案1】:

根据文档:

collection_select(method, collection, value_method, text_method, 选项 = {}, html_options = {}) 公开

因此你应该使用:

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

【讨论】:

  • 我的有什么区别,我的@channels 应该有收藏吗?
  • 没有区别。您可以根据您的示例使用@channels。
  • 附加问题,为什么这不起作用:{prompt: t ("channel.add.prompt")}
  • prompt 需要一个字符串值或布尔值。你想做什么?
  • 我想从我的语言环境中加载一个字符串进行翻译
【解决方案2】:

你可以像这样使用

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.
)

【讨论】:

  • 这不使用表单构建器对象,这意味着当视图被渲染时,任何现有的值都不会被 Rails 自动预选。
【解决方案3】:

试试这个

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

【讨论】:

  • 我得到了这个错误:参数数量错误(3 for 4..6)
  • 这个怎么样?
  • 这些都没有为 collection_select 方法提供正确的参数
  • 现在我得到了这个:undefined method `map' for :id:Symbol
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-12-22
  • 1970-01-01
  • 2019-02-10
  • 1970-01-01
  • 2014-09-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多