2015-08-21 41 views
0

在Rails項目中,如果它屬於單個用戶,我試圖生成類別名稱的數組。生成陣列的角色,以響應在Rails中具有多個角色的單個用戶

例如,用戶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"} 
] 

總之,我想放在類別名稱中的一個陣列。

+0

這個問題似乎已經過時了,並刪除。 Rubyist,供將來參考:當人們幫助你時,「不工作」很難用足夠的反饋來描述某人的建議是否奏效。請記住,你是讀者的眼​​睛和耳朵,如果你沒有提供任何反饋,那麼幫助你的人沒有什麼新的工作。 – halfer

+0

可能在以下情況下被封閉:_尋求調試幫助的問題(「爲什麼這個代碼不工作?」)必須包含所需行爲,特定問題或錯誤以及在問題本身中重現問題所需的最短代碼。 – halfer

回答

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 
+0

不工作... – Rubyist

0
[{"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"} 
].reduce({}) do |m, e| 
    found = (m[e["city"]] ||= {status: e['status'], names: [], city: e['city']}) 
    found[:names] << e['name'] 
    m 
end.values 

=> [{:狀態=>真實,:名稱=> [ 「地主」, 「ProperyBroker」]:城市= >「Mumbai」}, {:status => true,:names => [「Tenant」],:city =>「Delhi」}]

+0

不工作... – Rubyist

相關問題