2013-08-04 17 views
2

我有這個collection_select <%= collection_select(:template, :template_id, @templates, :id, :name) %>,我想基本上調用:name.humanize,但顯然這是行不通的。 (?哈希屬性)Rails如何調用助手,如.humanize上的屬性collection_select

我如何可以調用的方法,如.humanize上collection_select的屬性

編輯

下面是從我的控制器的一個片段:

@templates = Template.select(:name).group(:name) 
p "templates = #{@templates}" 

這裏的控制檯中顯示的內容:

"templates = #<ActiveRecord::Relation:0x007f84451b7af8>" 
+0

建設@templates對象時,我會做這個之前,做你自己,通過準備您的數據。 – Candide

+0

是的,贊同@Candide,我可能會有另一個幫助做這種事情的屬性。 –

+0

您可以詳細說明嗎?也許有一些代碼? – Catfish

回答

7

使用Rails 4

就像這樣:

<%= collection_select(:template, :template_id, @templates, :id, Proc.new {|v| v.name.humanize}) %>

Proc塊,v將是您的模型,通過each循環迭代。

collection_select適用於任何從Enumerable繼承的內容,並且對Proc的內容沒有限制。

使用Rails 3

你必須將它傳遞給collection_select

# This will generate an Array of Arrays 
values = @templates.map{|t| [t.id, t.name.humanize]} 
# [ [record1.id, record1.name.humanize], [record2.id, record2.name.humanize], ... ] 

# This will use the Array previously generated, and loop in it: 
# - send :first to get the value (it is the first item of each Array inside the Array) 
# - send :last to get the text (it is the last item of each Array inside the Array) 
#  (we could have use :second also) 
<%= collection_select(:template, :template_id, values, :first, :last) %> 
+0

變量'v'從哪裏來?我嘗試了這個,因爲你有它,它給了我一個錯誤'#不是一個符號' – Catfish

+0

改進我的回答 – Benj

+0

對不起,因爲如此密集,但你是說Proc的'v'值來自我的'@ templates'變量嗎?我用更多的信息編輯了我的問題,因爲我仍然收到我以前的評論中的錯誤。 – Catfish