2010-09-04 5 views
11

Ich brauche eine Sammlung zum Standardauswahleingang in Formtastic weitergeben muß:Wie man richtig für die Eingabe in Formtastic Sammlung passiert

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

Das Problem ist aber, dass ich Formtastic muß als Name eine andere Methode zuzugreifen. Das ist wirklich ein Problem. Ich kann immer das Array passieren

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

Das Problem ist, dass diese, nachdem ich Strings in der Steuerung statt IDs erhalten wird, die nicht erwünscht ist. Ich habe versucht, Hash stattdessen weitergeben müssen:

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

Das Problem ist jetzt, dass ich da bin mit Ruby-1.8.7, die Hash, um nicht spezifiziert ist und ich natürlich Notwendigkeit Eingang bestellt ...

ich kann Stellen Sie sich einige Lösungen vor, aber all diese erfordern unnötigen Code.

Irgendeine Idee, wie man dieses Recht löst?

Antwort

15

Versuche:

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

was ist, wenn wir nicht nur wollen: format_name, aber etw so:: format_name +: another_name? – kokemomuke

4

Es gibt keine direkte Anzeige in der formtastic Dokumentation, aber Sammlung kann auch verschachtelte Arrays werden, so Problem gelöst:

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

Das hat den Trick für mich gemacht, wie ich zufällig noch eine Ruby 1.8.7 Version benutze. Vielen Dank! – shakerlxxv

0

Dies ist der richtige Weg, jetzt: Dieses

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

setzt collection auf ein Array von [Name, id] Tupel. Einfach!

Soon-to-be veraltet Weise:

Verwenden Sie die member_label Option, zum Beispiel

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

Dokumentation ist here in a code comment.