How to make a Rails 3 Dynamic Scope Conditional?

后端 未结 1 1163
春和景丽
春和景丽 2021-01-31 19:08

I\'d like to make a dynamic named scope in rails 3 conditional on the arguments passed in. For example:

class Message < AR::Base
  scope :by_users, lambda {|u         


        
1条回答
  •  长发绾君心
    2021-01-31 19:22

    To answer your question you can do:

    scope :by_users, lambda {|user_ids| 
      where(:user_id => user_ids) unless user_ids.empty?
    }
    

    However

    I normally just use scope for simple operations(for readability and maintainability), anything after that and I just use class methods, so something like:

    class Message < ActiveRecord::Base
    
      def self.by_users(users_id)
        if user_ids.empty?
          scoped
        else
          where(:user_id => users_id)
        end
      end
    
    end
    

    This will work in Rails 3 because where actually returns an ActiveRecord::Relation, in which you can chain more queries.

    I'm also using #scoped, which will return an anonymous scope, which will allow you to chain queries.

    In the end, it is up to you. I'm just giving you options.

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