我有一个像这样的select_tag:
<%= select_tag "User Groups", options_from_collection_for_select(@user_groups, "id", "name") %>
这是我的模特
class Entity < ActiveRecord::Base
has_many :user_groups
end
class UserGroup < ActiveRecord::Base
belongs_to :entity
end
需要注意的是,UserGroup模型没有名为“name”的属性,但实体模型中有一个属性。
理想情况下,我想将实体模型中“name”属性的值传递给options_from_collection_for_select()方法......就像这样:
<%= select_tag "User Groups", options_from_collection_for_select(@user_groups, "id", @user_groups.each{|user_group| user_group.entity.name}) %>
但后来我得到了这样的东西:
[#<UserGroup id: 1, entity_id: 3, created_at: "2012-03-15 02:36:28", updated_at: "2012-03-15 02:36:28">, #<UserGroup id: 2, entity_id: 4, created_at: "2012-03-15 02:42:36", updated_at: "2012-03-15 02:42:36">] is not a symbol
有没有办法可以使用options_from_collection_for_select()并将嵌套属性中的值作为选项文本传递?
答案 0 :(得分:4)
如果将其添加到UserGroup模型中:
def entity_name
self.entity.name
end
然后你可以做
<%= select_tag "User Groups", options_from_collection_for_select(@user_groups, "id", "entity_name") %>
答案 1 :(得分:1)
options_from_collection_for_select
也接受lambda作为text_method
参数。
<%= select_tag "User Groups", options_from_collection_for_select(
@user_groups,
"id",
lambda { |user_group| user_group.entity.name} )
%>
如果你有一些特定于视图的代码,你不想用它来污染模型,那么你可以将自定义方法放在视图中。