ActiveRecord查询多个连接

时间:2015-02-06 17:59:01

标签: ruby-on-rails activerecord

我有以下型号:

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表。 我无法弄清楚如何编写ActiveRecord查询以获取特定用户的所有Planograms。我尝试了以下方法:

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

以及许多其他组合,但我在ActiveRecord查询中没有经验。

3 个答案:

答案 0 :(得分:2)

您可以将用户和计划图关联起来:

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

获取特定用户的计划图:

user.planograms

答案 1 :(得分:1)

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

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

您可以在此处阅读ActiveRecord联接方法的更多内容:http://guides.rubyonrails.org/active_record_querying.html#joining-tables

答案 2 :(得分:0)

我只想使用Arel。首先通过执行以下操作获取模型的arel表:

planograms = Planogram.arel_table
epics = Epic.arel_table

然后按以下方式创建您的查询:

Planogram.joins(:epic).where(epics[:user_id].eq(USER_ID))
相关问题