ActiveRecord 查询多个连接

ActiveRecord querying multiple joins

我有以下型号:

class Epic < ActiveRecord::Base
  has_many :planograms
  has_and_belongs_to_many :users
end

class Planogram < ActiveRecord::Base
  belongs_to :epic
end

class User < ActiveRecord::Base
  has_and_belongs_to_many :epics
end

还有一个 epics_users table。 我不知道如何编写 ActiveRecord 查询来获取特定用户的所有货架图。我尝试了以下方法:

Planogram.joins(:epic).where(:epics_users => {:user_id => 1})

和许多其他组合,但我在 ActiveRecord 查询方面经验不足。

您可以像这样关联用户和货架图:

class User < ActiveRecord::Base
  has_and_belongs_to_many :epics
  has_many :planograms, :through => :epics
end

并获取特定用户的货架图:

user.planograms

我会简单地使用 Arel。首先通过执行以下操作获取模型的 arel 表:

planograms = Planogram.arel_table
epics = Epic.arel_table

然后按如下方式创建查询:

Planogram.joins(:epic).where(epics[:user_id].eq(USER_ID))

在这种情况下,与用户的关系是通过Epic。你可以试试这个:

Planogram.joins(epic: :users).where(:epics_users => {:user_id => 1})

您可以在此处阅读有关 ActiveRecord 的连接方法的更多信息:http://guides.rubyonrails.org/active_record_querying.html#joining-tables