【问题标题】:How to properly pass collection for input in Formtastic如何在 Formtastic 中正确传递集合以进行输入
【发布时间】:2010-09-04 15:52:03
【问题描述】:

我需要将一个集合传递给 Formtastic 中的标准选择输入:

f.input :apple, :as => :select, :collection => Apple.all

问题是,尽管我需要 Formtastic 来访问与名称不同的方法。现在这确实是一个问题。我总是可以通过数组

f.input :apple, :as => :select, :collection => Apple.map { |a| a.format_name }

问题是,在此之后我将在控制器中获取字符串而不是不需要的 ID。我试图通过 Hash 代替:

options = Hash.new
Apple.each { |a| Apple.store(a.format_name, a.id) }
f.input :apple, :as => :select, :collection => options

现在的问题是,由于我使用的是 Ruby 1.8.7,哈希顺序是未指定的,我当然需要有序输入...

我可以想象一些解决方案,但所有这些都需要不必要的代码。

知道如何解决这个问题吗?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 formtastic


    【解决方案1】:

    试试:

    f.input :apple, :as => :select, :collection => Apple.all, :label_method => :format_name, :value_method => :id
    

    【讨论】:

    • 如果我们不仅想要 :format_name,而且像这样::format_name + :another_name 怎么办?
    【解决方案2】:

    formtastic文档中没有直接说明,但是collection也可以是嵌套数组,所以问题是这样解决的:

    f.input :apple, :as => :select, :collection => Apple.map { |a| [ a.format_name, a.id ] }
    

    【讨论】:

    • 这对我有用,因为我碰巧仍在使用 Ruby 1.8.7 版本。谢谢!
    【解决方案3】:

    这是现在正确的方法:

    f.input :apple,
            as: :select,
            collection: Apple.pluck(:format_name, :id)
    

    这会将 collection 设置为 [name, id] 元组数组。简单!

    即将弃用的方式:

    使用member_label 选项,例如

    f.input :apple,
            as: :select,
            collection: Apple.all,
            member_label: :format_name
    

    文档是here in a code comment

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-12
      • 2021-12-28
      • 1970-01-01
      • 2018-12-22
      • 2016-02-14
      相关资源
      最近更新 更多