如何使用 Rails 定义与当前用户具有相同元素的用户



我正在尝试创建一个函数,根据新用户选择的类别向新用户显示推荐的用户。

因此,推荐的用户应user_type:"星号",并且它具有与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

很抱歉解释令人困惑,但任何事情都有帮助。谢谢!

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

相关内容

最新更新