2012-07-27 69 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