【问题标题】:rails average between multiple models多个模型之间的平均轨道
【发布时间】:2010-11-24 21:06:33
【问题描述】:

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

【问题讨论】:

    标签: sql ruby-on-rails ruby relational


    【解决方案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
    

    【讨论】:

      【解决方案2】:

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

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

      使用后效果很好

      :has_many, :through => :model
      

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-10
        • 1970-01-01
        • 1970-01-01
        • 2012-08-17
        • 1970-01-01
        相关资源
        最近更新 更多