多个型号之间的导轨平均值
我一直在尝试使用 Rails 关系做事,而不是拉出大型 SQL 连接,但我无法集中精力解决这个问题...
我有 3 个模型
酒店 客房 可用
它们都具有适当的 has_many 和 Belongs_to 关系。
我想要做的是在概述页面上列出特定城市的酒店,我想列出每个酒店找到的最低价格。
现在在 SQL 中我当然会在底部做一些代码,但是在 Rails 中我可以做这样的事情...
def self.price
Available.minimum(:price,
:conditions => [ "price <> 0" ])
end
这当然只是拉出所有这些的最低价格,而不是特定的 ID
问题是关系Hotel.find(1234).rooms.availables
但我想做这样的事情,可以进入我的循环而无需引用 ID?
SELECT MIN(availables.price)
FROM availables
INNER JOIN rooms ON rooms.id = availables.room_id
INNER JOIN hotels ON hotels.id = rooms.hotel_id
WHERE hotels.id = 5077 and rooms.private = 0 and availables.price <> 0
I've been trying to get my head around doing things using my Rails relationships as opposed to pulling out large SQL joins, but I can't wrap my head around this one...
I have 3 models
Hotels
Rooms
Availables
They all have the appropriate has_many and belongs_to relationships.
What I want to do is on the overview page listing the Hotels of a particular City, i want to list the lowest price found for each hotel.
Now in SQL I would of course do the bit of code at the bottom, but in rails I could do something like this...
def self.price
Available.minimum(:price,
:conditions => [ "price <> 0" ])
end
This of course just pulls the lowest price of all of them, not a specific ID
The problem is the relationship Hotel.find(1234).rooms.availables
But I'd like to do something like this that could go inside my loop without having to reference the ID?
SELECT MIN(availables.price)
FROM availables
INNER JOIN rooms ON rooms.id = availables.room_id
INNER JOIN hotels ON hotels.id = rooms.hotel_id
WHERE hotels.id = 5077 and rooms.private = 0 and availables.price <> 0
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以通过在 Hotel 上设置 has_many :through 关系来实现此目的:
现在您可以循环遍历特定城市中显示最低价格的所有酒店:
You can accomplish this by setting up a has_many :through relationship on Hotel:
Now you can loop through all of the hotels in a particular city displaying the lowest price:
没关系!答案就在我面前,我只是没有得到正确的关联。
使用后效果非常好,
我只是没有意识到我必须设置更复杂的关系才能使其正常工作......
Nevermind! The answer was right in front of me, i just didn't get the proper association.
This works perfectly after using
I just didn't realize I had to setup a more complex relationship in order for it to work properly...