2011-01-08 86 views
5

我有一個叫appointment的模型。每個appointment有一個stylist。在我創建一個新appointment形式,我這樣做:Rails關聯和表單

<div class="field"> 
    <%= f.label :stylist_id %><br /> 
    <%= f.select(:stylist_id, Stylist.order("name").map { |s| [s.name, s.id] }) %> 
    </div> 

這工作,但它的將是乏味做這種事情在我的應用程序的每個關聯。我想Rails有一些自動生成關聯選擇字段的方法,但我不知道它是如何工作的。這樣的事情存在嗎?

哦,順便說一下,我已經知道腳手架。如果腳手架應該照顧我上面所描述的,我顯然做錯了事,因爲它不是爲我做的。

(我on Rails的3)

+0

嗯...你曾經使用Formtastic或任何外部形式的寶石考慮? – Rekin 2011-01-08 21:14:26

+0

你可能應該檢查Formtastic爲那種行爲。 https://github.com/justinfrench/formtastic – 2011-01-08 21:14:44

回答

23

嗯,似乎collection_select將針對典型方案工作:

<%= f.collection_select :stylist_id, Stylist.all, :id, :name %> 
1

據我所知Rails的沒有一個簡單的方法來創建選擇標籤。您可以使用像formtastic(https://github.com/justinfrench/formtastic)或simple_form(https://github.com/plataformatec/simple_form)這樣的gem,這使創建表單變得更容易。我更喜歡simple_form我自己,所以我建議你嘗試一下。

另一種方法是創建自己的選擇幫助程序,該幫助程序會自動從數據庫獲取關聯的記錄。你也可以把Stylist.order...東西的模型中:

# Model 
def self.select 
    Stylist.order("name").map { |s| [s.name, s.id] } 
end 

# Form 
<%= f.select(:stylist_id, Stylist.select) %> 

讓您的觀點看上去有點更好。 :)

4

多達RobinBrouwer的答案是正確的,我只是想分享一個小金塊,我想出了在工作中我們的應用程序之一:

# config/initializers/to_options.rb 
module ActiveRecord 
    class Base 
    def self.to_options(title=:name) 
     self.all.map{|r| [r.send(title), r.id]} 
    end 
    end 
end 

現在,你可以在任何模型中使用to_options ,可以靈活地爲選項文本選擇任何字段(默認爲name)。

Model.to_options # => Creates select options with [m.name, m.id] 
AnotherModel.to_options(:title) # => Creates select options with [m.title, m.id] 

不應該是很難與訂購如果需要的話,要麼修改。