生成角色数组以响应在Rails中具有多个角色的单个用户

时间:2015-08-21 17:56:32

标签: ruby-on-rails arrays

在Rails项目中,如果它属于Single User,我正在尝试生成Category的名称数组。

例如,用户A有两个类别,如LandLord和PropertyBroker。

用户模型

class User < ActiveRecord::Base

  has_many :users_categories
  has_many :categories, through: :users_categories

  scope :users_categories_active, -> { joins(:users_categories)
                                       .where('users_categories.status = ?', true) }
  def self.with_selected_active_user
    select("users.id, users.first_name, users.city, categories.name,
                                           users_categories.status, users_categories.id")
  end
end

类别模型

class Category < ActiveRecord::Base
  has_many :users_categories
  has_many :users, through: :users_categories
end

UserCategory模型

class UserCategory < ActiveRecord::Base
  belongs_to :user
  belongs_to :category
end

查询

user_list = User.joins(:categories, :users_categories)
                         .with_selected_active_user.users_categories_active.uniq
render :json => user_list

输出

[{"id":2,"first_name":"Adam","city":"Mumbai","status":true,"name":"LandLord"},
 {"id":3,"first_name":"Charles","city":"Delhi","status":true,"name":"Tenant"},
 {"id":1,"first_name":"Adam","city":"Mumbai","status":true,"name":"ProperyBroker"}
]

我试图以不同的模式生成此输出

 [{"first_name":"Adam","city":"Mumbai","status":true,"name":"['LandLord','ProperyBroker'"},
 {"first_name":"Charles","city":"Delhi","status":true,"name":"Tenant"} 
 ]

总而言之,我想将类别名称放在一个数组中。

2 个答案:

答案 0 :(得分:0)

在您的查询中使用group,如下所示 -

user_list = User.joins(:categories, :users_categories)
              .with_selected_active_user.users_categories_active.group(" first_name, city, status, name ")
render :json => user_list 

答案 1 :(得分:0)

{{1}}

=&GT; [{:status =&gt; true,:names =&gt; [“LandLord”,“ProperyBroker”],:city =&gt;“Mumbai”},  {:status =&gt; true,:names =&gt; [“Tenant”],:city =&gt;“Delhi”}]