Check if model instance falls within named_scope in rails

后端 未结 2 1010
眼角桃花
眼角桃花 2021-02-14 18:23

Assume I have a named scope:

class Foo < ActiveRecord::Base
    named_scope :bar, :conditions => \'some_field = 1\'
end

This works great

相关标签:
2条回答
  • 2021-02-14 18:42

    You can call the exists? method on a named scope which will query the database to see if the given record exists with those conditions.

    Foo.bar.exists?(f)
    

    However this will not work if you have changed the attributes on f and not saved it to the database. This is because the named scope conditions are SQL so the check must happen there. Attempting to convert to Ruby if conditions is messy, especially in more complex scenarios.

    0 讨论(0)
  • 2021-02-14 18:53

    If your scopes are simple, you probably want to avoid code duplication. My solution allows you to call model.active? to know if an instance belongs to the scope, and Model.active to find all records matching the scope. model.active? doesn't involve any database queries.

    consider adding this to config/initializers/scope_and_method.rb:

    require 'active_record/named_scope'
    
    module ActiveRecord::NamedScope::ClassMethods
      def scope_and_method field, *values
        field = field.to_sym
        values.each do |value|
          named_scope value.to_sym, :conditions => {field => value}
          define_method "#{value}?" do
            send(field.to_sym) == value
          end
        end
      end
    end
    

    Usage:

    scope_and_method :state, 'active', 'inactive'
    

    Works as if it was:

    named_scope :active, :conditions => {:state => 'active'}
    named_scope :inactive, :conditions => {:state => 'inactive'}
    
    def active?
      state == 'active'
    end
    
    def inactive?
      state == 'inactive'
    end
    

    This is a solution for Rails 2.3. This needs a very small tuning for Rails 3 and 4. (named_scope -> scope) I will check it soon.

    0 讨论(0)
提交回复
热议问题