2009-12-20 100 views
11

我是Rails的新手,正在使用collection_select方法。Ruby on Rails collection_select顯示屬性

我有兩個領域,我想在我的選擇框中顯示:

first_namelast_name

到目前爲止,我只能顯示一個或另一個,而不是兩個。

這裏是我的工作代碼:

collection_select(:hour,:shopper_id,@shoppers,:id,"last_name") 

謝謝。

回答

24

添加full_name方法shopper型號:

class Shopper < ActiveRecord::Base 
    #..... 
    # add this 
    def full_name 
    "#{first_name} #{last_name}" 
    end 
end 

並修改collection_select聲明:

collection_select(:hour,:shopper_id,@shoppers,:id,:full_name) 

這是因爲大多數的Rails的helper需要方法名作爲參數,可以這樣做collection_select,這需要一個text_method帕拉姆,這是要調用的方法的名稱,以生成該選項本身的文本,因此我們定義full_name方法,我們傳遞它的名字t o collection_select

+0

太好了,謝謝! – New2rails 2009-12-20 16:54:47