如何从具有一对一关联的三个模型中获取记录?

时间:2016-07-29 06:21:21

标签: ruby-on-rails associations one-to-one

我有三个模特。它们如下定义:

#Checkout Model
class Checkout < ActiveRecord::Base
    belongs_to :gallery_visitor
end

#GalleryVisitor Model
class GalleryVisitor < ActiveRecord::Base
  belongs_to :gallery
  has_one :checkout
end

#Gallery Model
class Gallery < ActiveRecord::Base
    has_many :gallery_visitors, dependent: :destroy
end

我愿意在结帐模式的基础上获取所有画廊。 我怎样才能使用includes()? 谁能帮我吗?谢谢你的推荐。

2 个答案:

答案 0 :(得分:2)

嘿,你可以这样试试:

Gallery.includes({gallery_visitors: [:checkout]}).where(checkouts: {condition})

答案 1 :(得分:1)

您甚至可以通过添加来自

的关联来进行此查询 shorter quicker Gallery to Checkout through Gallery Visitors more rails 方式。

将行has_one :checkout,through: :gallery_visitors添加到图库模型

class Gallery < ActiveRecord::Base
    has_many :gallery_visitors, dependent: :destroy
    has_one :checkout,through: :gallery_visitors
end

重新加载控制台,然后尝试此查询

Gallery.includes(:checkout).where(checkout: {condition})

Eg: Gallery.includes(:checkout).where(checkout: {id: 1})

这可以直接关系并使查询更快。