Ruby on rails 如何从具有一对一关联的三个模型中获取记录?
我有三个模型。它们的定义如下:Ruby on rails 如何从具有一对一关联的三个模型中获取记录?,ruby-on-rails,associations,one-to-one,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
#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()获取?
有人能帮我吗?非常感谢您的帮助。嘿,您可以这样尝试:
Gallery.includes({gallery_visitors: [:checkout]}).where(checkouts: {condition})
嘿,你可以这样试试:
Gallery.includes({gallery_visitors: [:checkout]}).where(checkouts: {condition})
您甚至可以通过添加以下项的关联,使此查询
更短
和更快
通过图库访问者以更多rails的方式查看图库
将行has_one:checkout,through::gallery_visitors
添加到gallery模型中
class Gallery < ActiveRecord::Base
has_many :gallery_visitors, dependent: :destroy
has_one :checkout,through: :gallery_visitors
end
类库
重新加载控制台,然后尝试此查询
Gallery.includes(:checkout)。其中(checkout:{condition})
Eg:Gallery.includes(:checkout)。其中(checkout:{id:1})
这将建立直接关系,并使查询更快。您甚至可以通过添加以下项的关联,使此查询更短
,更快
通过图库访问者以更多rails的方式查看图库
将行has_one:checkout,through::gallery_visitors
添加到gallery模型中
class Gallery < ActiveRecord::Base
has_many :gallery_visitors, dependent: :destroy
has_one :checkout,through: :gallery_visitors
end
类库
重新加载控制台,然后尝试此查询
Gallery.includes(:checkout)。其中(checkout:{condition})
Eg:Gallery.includes(:checkout)。其中(checkout:{id:1})
这就形成了一种直接的关系,使得查询速度更快。我认为他需要基于checkout@Deepak您的查询返回签出
而不是库。在上面的查询中,您可以将条件放在它将返回给您的签出模型上gallaries@vishal谢谢。这对我来说简直是个奇迹我认为他需要画廊的基础上checkout@Deepak您的查询返回签出
而不是库。在上面的查询中,您可以将条件放在它将返回给您的签出模型上gallaries@vishal谢谢。这对我来说简直是个奇迹