让我们说
另外
加入'projects'和'joined_projects'以获得用户有权访问的所有项目的最佳方式是什么,而不使用sql。
其他选项是为所有项目创建成员资格,即使用户拥有项目,但会在数据库上生成重复数据。
答案 0 :(得分:1)
join
中的ActiveRelation
方法始终使用内部联接,因此从SQL角度来看,无法“正确”执行此操作。但是,您始终可以设置counter_cache
并按如下方式进行查询:
class User < ActiveRecord::Base
has_many :projects, :counter_cache => true
has_many :joined_projects, :through => :memberships, :counter_cache => true
class << self
def has_projects
where('projects_count > 0 OR joined_projects_count > 0')
end
end
def all_projects
projects + joined_projects
end
end
它可能会达到正常化的神经,但应该完成工作。