代码之家  ›  专栏  ›  技术社区  ›  mdrozdziel

如何在Formtastic中正确传递输入集合

  •  12
  • mdrozdziel  · 技术社区  · 14 年前

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

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

    问题是,尽管我需要Formtastic来访问与name不同的方法。现在这真的是个问题。我总能通过阵法

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

    问题是,在此之后,我将在控制器中获得字符串,而不是不需要的id。我试着传递哈希:

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

    现在的问题是,因为我使用的是Ruby1.8.7,哈希顺序没有指定,我当然需要有序的输入。。。

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

    3 回复  |  直到 14 年前
        1
  •  16
  •   James Healy    14 年前

    尝试:

    f.input :apple, :as => :select, :collection => Apple.all, :label_method => :format_name, :value_method => :id
    
        2
  •  4
  •   mdrozdziel    14 年前

    formtastic文档中没有直接的指示,但集合也可以是嵌套数组,因此问题可以通过以下方法解决:

    f.input :apple, :as => :select, :collection => Apple.map { |a| [ a.format_name, a.id ] }
    
        3
  •  0
  •   Grant Birchmeier    8 年前

    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