Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly pass collection for input in Formtastic

I need to pass a collection to the standard select input in Formtastic:

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

The problem is, though that I need Formtastic to access a different method than name. Now this is really a problem. I can always pass the Array

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

The problem is, that after this I will get strings in the controller instead of IDs which is not desired. I tried to pass Hash instead:

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

Now the problem is, that since I am using Ruby 1.8.7, the Hash order is unspecified and I of course need ordered input...

I can imagine some solutions, but all of those require unnecessary code.

Any idea how to solve this right?

like image 918
mdrozdziel Avatar asked Sep 04 '10 15:09

mdrozdziel


3 Answers

This is the correct way now:

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

This sets collection to an array of [name, id] tuples. Easy!

Soon-to-be deprecated way:

Use the member_label option, e.g.

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

Documentation is here in a code comment.

like image 136
Grant Birchmeier Avatar answered Nov 03 '22 20:11

Grant Birchmeier


Try:

f.input :apple, :as => :select, :collection => Apple.all, :label_method => :format_name, :value_method => :id
like image 24
James Healy Avatar answered Nov 03 '22 22:11

James Healy


There is no direct indication in the formtastic documentation, but collection can be nested arrays as well, so problem is solved by:

f.input :apple, :as => :select, :collection => Apple.map { |a| [ a.format_name, a.id ] }
like image 4
mdrozdziel Avatar answered Nov 03 '22 20:11

mdrozdziel