代码之家  ›  专栏  ›  技术社区  ›  scrrr

按数量查找

  •  1
  • scrrr  · 技术社区  · 16 年前

    假设我有一个模型

    Vehicle
    

    而且它

    has_many :wheels
    

    正确的查找是什么?/:条件=>…仅查找带有3个或更多车轮的车辆的声明,例如三轮车、汽车、卡车、坦克等…?

    1 回复  |  直到 16 年前
        1
  •  3
  •   Community Mohan Dere    9 年前

    不一样,但我相信你可以通过回答这个问题来解决你的问题: Using named_scope with counts of child models

    简而言之:

    添加 wheels_count 列到车辆表中

    class Wheel < ActiveRecord::Base
      belongs_to :vehicle, :counter_cache => true # this will autoupdate the wheels_count on Vehicle
    end
    

    现在,您可以按车轮数搜索车辆:

    # for all Vehicles with 4 Wheels
    Vehicle.all(:condition => { :wheels_count => 4 })
    # or for all Vehicles with more than 3 Wheels
    Vehicle.all(:condition => ["wheels_count > ?", 3])
    

    更新:

    class AddWheelCount < ActiveRecord::Migration
      def self.up  
        add_column :vehicles, :wheels_count, :integer, :default => 0  
    
        Vehicle.reset_column_information  
        Vehicle.all.each do |p|  
          p.update_attribute :wheels_count, p.wheels.length  
        end  
      end  
    
      def self.down  
        remove_column :vehicles, :wheels_count  
      end
    end
    

    所以车轮计数设置为当前计数

    推荐文章