1

我一直在尝试使用我的 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
4

2 回答 2

1

没关系!答案就在我面前,我只是没有得到正确的联想。

  def self.price
    Available.minimum(:price,
              :conditions => [ "price <> 0" ])
  end

使用后效果很好

:has_many, :through => :model

我只是没有意识到我必须建立一个更复杂的关系才能使其正常工作......

于 2009-09-02T10:14:38.813 回答
1

您可以通过在 Hotel 上设置 has_many :through 关系来完成此操作:

class Hotel < ActiveRecord::Base
  has_many :rooms
  has_many :availables, :through => :rooms

  # If you want "rooms"."private" condition, use these...
  has_many :public_rooms, :class_name => 'Room', :conditions => {:private => 0}
  has_many :public_availables, :through => :public_rooms, :source => :availables

  # This caches the value (potentially saving you db hits) for the
  # lifetime of the object, which you may or may not want depending
  # on your needs...
  def cheapest_available
    @cheapest_available ||= availables.minimum(:price, :conditions => ['availables.price > ?', 0])
  end
end

现在您可以遍历显示最低价格的特定城市的所有酒店:

@city.hotels.each do |hotel|
  puts "#{hotel.name}: #{hotel.cheapest_available}"
end
于 2009-09-02T10:22:23.853 回答