Use a scope by default on a Rails has_many relationship

前端 未结 3 1046
难免孤独
难免孤独 2021-01-30 05:13

Let\'s say I have the following classes

class SolarSystem < ActiveRecord::Base
  has_many :planets
end

class Planet < ActiveRecord::Base
  scope :life_supp         


        
3条回答
  •  忘掉有多难
    2021-01-30 05:45

    In Rails 4, Associations have an optional scope parameter that accepts a lambda that is applied to the Relation (cf. the doc for ActiveRecord::Associations::ClassMethods)

    class SolarSystem < ActiveRecord::Base
      has_many :planets, -> { life_supporting }
    end
    
    class Planet < ActiveRecord::Base
      scope :life_supporting, -> { where('distance_from_sun > ?', 5).order('diameter ASC') }
    end
    

    In Rails 3, the where_values workaround can sometimes be improved by using where_values_hash that handles better scopes where conditions are defined by multiple where or by a hash (not the case here).

    has_many :planets, conditions: Planet.life_supporting.where_values_hash
    

提交回复
热议问题