我有3个模型User,Company和Privilege,关系如下
user.rb
has_many :privileges
has_many :companies, through: :privileges
company.rb
has_many :privileges
has_many :users, through: :privileges
privilege.rb
belongs_to :company
belongs_to :user
现在我希望公司为具有所有权限的用户
我尝试了一些来自stackoverflow和文档的解决方案,但我无法获得理想的结果
user = User.find(1)
user.companies.includes(:privileges).references(:privileges)
但是这不会返回我真正想要进一步处理的权限
任何帮助都将受到高度赞赏
答案 0 :(得分:1)
您不需要includes(:privileges)
,因为has_many :through
会生成内部联接
如果您需要特权,则需要申请。我认为这个请求会给你你所期望的:
Privilege.where(user_id: user.id)
如果您还需要检查公司ID是否存在:
Privilege.where(user_id: user.id).where.not(company_id: nil)