我想在结果(行)中添加键和值对,所以我喜欢这样:
row :skill_level do |user|
level = {}
user.try(:sport_memberships).each do |sport|
sport_name = Sport.where(id: sport.try(:sport_id)).try(:name)
sport_level = sport.try(:level)
level = level.merge!("#{sport_name.to_sym}" => sport_level)
end
end
模型的关联是:
user.rb
has_many :sport_memberships,
inverse_of: "user",
class_name: "Sport::Membership"
sport.rb
has_many :memberships
membership.rb
belongs_to :sport, inverse_of: "memberships", counter_cache: true
belongs_to :user, inverse_of: "sport_memberships"
我预计等级将返回如下值:{羽毛球:2,高尔夫:2},但实际的结果是:[#<Sport::Membership id: 5024, sport_id: 4, user_id: 976, level: 2, tribe_id: nil>, #<Sport::Membership id: 5025, sport_id: 14, user_id: 976, level: 2, tribe_id: nil>]
。看来我的循环没有按照我的期望运行。我该如何解决我的问题?
答案 0 :(得分:0)
首先覆盖控制器动作
未经过测试
def index
super
@levels = User.joins(sport_memberships: :sport).where(id: resource.id).select("sports.name, sport_memberships.level").group("sports.name, sport_memberships.level")
end
请尝试此查询,让我知道它是否正常工作。
答案 1 :(得分:0)
您似乎正在尝试构建哈希,您可以这样做:
row :skill_level do |user|
user.sport_memberships.each_with_object({}) do |mem,hsh|
hsh[mem.sport.name] = mem.sport.level
end.to_s
end
但是,您也可以像这样构建一个字符串:
row :skill_level do |user|
user.sport_memberships.map do |mem|
"#{mem.sport.name}: #{mem.sport.level}"
end.join(", ")
end
可选地,为了获得更好的索引性能,请在注册时添加以下内容:
controller do
def scoped_collection
super.include(sports_memberships: [:sports])
end
end