Ruby on rails Rails:筛选范围中的嵌套属性
我的模型具有以下关系:Ruby on rails Rails:筛选范围中的嵌套属性,ruby-on-rails,activerecord,rails-activerecord,Ruby On Rails,Activerecord,Rails Activerecord,我的模型具有以下关系: 建筑有许多房间s,其中有许多床s,其中有许多住宿s 我想渲染所有建筑s,但要在日期范围内创建住宿s。从其他答案中,我了解到我需要为构建模型创建范围,但我不知道如何在这个范围内过滤这些嵌套属性 编辑: 假设我有建筑1、2和3。每个建筑都有自己的房间s,其中有床s,其中有住宿s。假设只有建筑1有一个住宿在范围内。因此,返回的数据必须是: Building 1 ... Room n ... Bed n Accommo
建筑
有许多房间
s,其中有许多床
s,其中有许多住宿
s
我想渲染所有建筑
s,但要在日期范围内创建住宿
s。从其他答案中,我了解到我需要为构建
模型创建范围,但我不知道如何在这个范围内过滤这些嵌套属性
编辑:
假设我有建筑
1、2和3。每个建筑
都有自己的房间
s,其中有床
s,其中有住宿
s。假设只有建筑
1有一个住宿
在范围内。因此,返回的数据必须是:
Building 1
...
Room n
...
Bed n
Accommodation that is in range
Bed n+1
...
...
Building 2 (accommodation arrays in beds are empty since there are no accommodations that are in range)
...
Building 3 (accommodation arrays is beds are empty since there are no accommodations that are in range)
...
要返回所有建筑物,但要使用过滤后的住宿,包括:
includes(rooms: [beds: :accomodations]).where(accomodations: { created_at: start_date..end_date })
要返回所有建筑物,但要使用过滤后的住宿,包括:
includes(rooms: [beds: :accomodations]).where(accomodations: { created_at: start_date..end_date })
要避免在模型中编写过多嵌套的联接查询,请执行以下操作:
class Building
has_many :rooms
has_many :beds, though: :rooms
has_many :accommodations, through: :beds
end
class Room
belongs_to :building
has_many :beds
has_many :accommodations, through: :beds
end
class Bed
belongs_to :room
has_many :accommodations
has_one :building, through: :room
end
class Accommodation
belongs_to :bed
has_one :room, through: :bed
has_one :building, through: :room
end
这将允许您直接查询建筑。住宿
,ActiveRecord将为您加入中间表
然后在查询时只需使用:
Building.includes(:accommodations)
.where(accommodations: { created_at: start_time..end_time })
这将使用大多数数据库驱动程序在…之间创建一个WHERE'住宿
谜题的另一个关键部分是您没有过滤嵌套属性。更确切地说,上面发生的情况是,您正在使用。来避免在模型中编写过多嵌套的联接查询:
class Building
has_many :rooms
has_many :beds, though: :rooms
has_many :accommodations, through: :beds
end
class Room
belongs_to :building
has_many :beds
has_many :accommodations, through: :beds
end
class Bed
belongs_to :room
has_many :accommodations
has_one :building, through: :room
end
class Accommodation
belongs_to :bed
has_one :room, through: :bed
has_one :building, through: :room
end
这将允许您直接查询建筑。住宿
,ActiveRecord将为您加入中间表
然后在查询时只需使用:
Building.includes(:accommodations)
.where(accommodations: { created_at: start_time..end_time })
这将使用大多数数据库驱动程序在…
之间创建一个WHERE'住宿
谜题的另一个关键部分是您没有过滤嵌套属性。相反,上面发生的情况是,您使用的是。这只包括住宿创建日期在范围内的建筑,但我只想筛选住宿并返回所有建筑,然后使用左侧外部连接。这只包括住宿创建日期在范围内的建筑,但我只想筛选住宿并返回所有建筑,然后改用左侧外部连接。这仅包括住宿创建日期在范围内的建筑,但我只想筛选住宿并返回所有建筑buildings@KudayarPirimbaev不幸的是,你的评论对我来说毫无意义。你能换一种说法吗?假设我有1号、2号、3号楼,1号楼有1个在范围内的住所,1个不在范围内,其他建筑根本没有。您的解决方案将返回1号楼的所有住宿,而我需要返回1号楼的范围内的住宿和其他住宿buildings@KudayarPirimbaev那么结果会是什么呢?有配套住宿的建筑?我的意思是,我需要在建筑内部过滤住宿,而不仅仅是满足住宿条件的建筑这只包括住宿创建日期在范围内的建筑,但我只想过滤住宿并归还所有buildings@KudayarPirimbaev不幸的是,你的评论对我来说毫无意义。你能换一种说法吗?假设我有1号、2号、3号楼,1号楼有1个在范围内的住所,1个不在范围内,其他建筑根本没有。您的解决方案将返回1号楼的所有住宿,而我需要返回1号楼的范围内的住宿和其他住宿buildings@KudayarPirimbaev那么结果会是什么呢?有配套住宿的建筑?我的意思是,我需要在建筑内部过滤住宿,而不仅仅是住宿条件令人满意的建筑