2016-02-18 22 views
2

我正試圖根據新用戶選擇的類別,向新用戶顯示推薦用戶的功能。如何用Rails定義與當前用戶具有相同元素的用戶?

所以建議用戶應該是user_type:「star」,它與current_user所選的category.id相同。

這些是模型。

class User < ActiveRecord::Base 
has_many :categorizings, as: :categorizable, dependent: :destroy 
has_many :categories, through: :categorizings 
end 

class Categorizing < ActiveRecord::Base 
belongs_to :category 
belongs_to :categorizable, polymorphic: true 
end 


class Category < ActiveRecord::Base 
has_many :categorizings, dependent: :destroy 
has_many :users, through: :categorizings, source: :categorizable, source_type: 'User' 
end 

而且,這是我的僞編碼方法來發現我卡在推薦用戶...

CategoriesController < ApplicationController 
def recommended_user 
    @recommended_user = User.where(user_type: 'star' && Who has same category.id with a current_user) 
end 
end 

很抱歉的混亂的解釋,但任何幫助。 謝謝!

+0

如果所有類別匹配,或任何在集合? – Vasfed

+1

你的應用中有'current_user' helper嗎? – Ilya

+0

是的,我的應用程序中有current_user helper。 – Ryuji

回答

1
@recommended_user = User 
        .joins(:categories) 
        .where(
         users: { user_type: 'star' }, 
         categories: { id: current_user.categories.first.id } 
        ) 
+0

非常感謝你! – Ryuji

0
@recommended_user = User.where(user_type: 'star').where(category_id: current_user.category_id) 
+0

用戶不屬於類別,因此它不會有'category_id'列 –