我有一个场景,我通过lambda获取业务组并收集要作为json发送的数据。
代码在这里:
def get_business_with_details
businesses = self.business_groups
binding.pry
businesses.collect do |business|
{
name: business.actor.name,
id: business.access_key,
is_business_admin: business.is_admin_user(self.id)
}
end
end
业务组的lambda代码在这里:
class User
has_many :business_groups, lambda { |user| where ["(groups.group_type
= 7 )"] }, through: :group_members, source: :group
end
我需要订购商业行为者名称的数据,即business.actor.name
答案 0 :(得分:2)
最终代码看起来像这样
def get_business_with_details
businesses = self.business_groups.includes(:actor)
businesses = businesses.collect do |business|
{
'name' => business.actor.name,
'id' => business.access_key,
'is_business_admin' => business.is_admin_user(self.id)
}
end
businesses = businesses.sort_by { |hsh| hsh['name'] }
businesses.to_json #final return value i.e. json converted and sorted by name
end
我希望这有帮助!
答案 1 :(得分:0)
def get_business_with_details
self.business_groups.
joins(:actor).
order('actor.name').
map do |business|
%w[name id is_business_admin].zip(
business.actor.name, business.access_key, business.is_admin_user(self.id)
).to_h
end.to_json
end