在 rails 中轻松检索双嵌套模型的所有实例
Easily retrieving all instance of a double nested model in rails
我有 Account has_many Hotels
和 Hotel has_many Rooms
因此我可以写 account.hotels
获取特定帐户的所有酒店,并 hotel.rooms
获取特定酒店的所有房间。
如果我想获取特定帐户的所有房间怎么办?有没有一种优雅的方法可以使用 rails 来做到这一点,而不必遍历帐户的每个酒店并将其存储在一个数组中?
像 account.hotels.rooms
?
这样的东西
上的 has_many :through
class Account < ActiveRecord::Base
...
has_many :hotels
has_many :rooms, through: :hotels
end
然后
account.rooms
我有 Account has_many Hotels
和 Hotel has_many Rooms
因此我可以写 account.hotels
获取特定帐户的所有酒店,并 hotel.rooms
获取特定酒店的所有房间。
如果我想获取特定帐户的所有房间怎么办?有没有一种优雅的方法可以使用 rails 来做到这一点,而不必遍历帐户的每个酒店并将其存储在一个数组中?
像 account.hotels.rooms
?
has_many :through
class Account < ActiveRecord::Base
...
has_many :hotels
has_many :rooms, through: :hotels
end
然后
account.rooms