在轨道上订购lambda

时间:2018-03-07 05:43:32

标签: ruby-on-rails ruby

我有一个场景,我通过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

2 个答案:

答案 0 :(得分:2)

  • 首先遍历每个商家并创建哈希数组。
  • 然后使用特定键值(即名称键)对哈希数组进行排序。
  • 然后将排序后的哈希数组转换为json。

最终代码看起来像这样

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