2012-07-27 66 views
2

我已經看到RailsCasts#302,它描述了使用best_in_place gem進行就地編輯。在那裏爲性別選項Ryan使用show.html.erb中的數組,並使其成爲一個下拉框(請參閱他明確定義數組的性別部分)。Rails-就地編輯使用best_in_place gem編輯模型本身定義的數組集合

<p> 
    <b>Gender:</b> 
    <%= best_in_place @user, :gender, type: :select, collection: [["Male", "Male"], ["Female", "Female"], ["", "Unspecified"]] %> 
</p> 

但我想是我定義的模型本身就像一個數組裏面(因爲我的數組元素不是簡單的和短期的計數)

對於如:

用戶。 RB

class User < ActiveRecord::Base 
    def authencity_types 
    ['Asian', 'Latin-Hispanic', 'Caucasian'] 
    end 
end 

我怎麼使用best_in_place語法使用這個數組元素下拉。

PS:我沒有嘗試這樣的事情

<% @users.each do |user| %> 
    <%= best_in_place user, :authencity, type: :select, :collection => User::authencity_types %> 
<% end %> 

但它說未定義的方法authencity_types

回答

4

你定義的用戶模型的實例方法,那麼試試這個。

<% @users.each do |user| %> 
    <%= best_in_place user, :authencity, type: :select, :collection => user.authencity_types %> 
<% end %> 

或者,您可以將其定義爲這樣的類方法。

class User < ActiveRecord::Base 
    def self.authencity_types 
    ['Asian', 'Latin-Hispanic', 'Caucasian'] 
    end 
end 

或者你可能想考慮使用一個常量,如果它不需要是動態的。

+0

工作正常!非常感謝瑞恩! :)我知道有很小的基本的東西讓我煩惱..但困惑。 – uday 2012-07-28 05:04:04

+1

出於某種原因,它只顯示第二個字符或每個數組,所以我把我的數組作爲數組的數組,它工作。 '['亞洲','亞洲'],['拉丁西班牙裔','拉丁西班牙裔'],['高加索人','高加索人']]' – uday 2012-07-28 08:44:52