【问题标题】:Rails: dependent scopes with conditionalsRails:带有条件的依赖范围
【发布时间】:2012-09-26 19:35:08
【问题描述】:

我有以下带有范围的用户对象:

Class User < ActiveRecord::Base
  ...
  scope :vendors,   lambda { where(:user_type => 'v') }
  scope :customers, lambda { where(:user_type => 'c') }
  ...

我想创建一个新的 inactive 范围,它对供应商和客户的行为有所不同,例如在伪代码中

  scope :inactive, lambda {
    if (:user_type => 'v')
      where(some_condition_only_for_vendors)

    elsif (:user_type => 'c')
      where(different_condition_only_for_customers)

    else
      where(another_condition)

    end
  }

这样,我可以使用users.vendors.inactive 之类的操作来根据一组条件获取所有不活跃的供应商,并使用users.customers.inactive 来根据另一组条件获取所有不活跃的客户。

这是可能的还是有更好的方法来做到这一点?请注意,这里有很多遗留代码,因此实现继承可能不可行。

谢谢!

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 scope


    【解决方案1】:

    我立即看到的问题是您从类中调用了一个范围,并且没有记录实例来获取 user_type。

    User.inactive
    

    所以你可能有类似的东西:

    class User < ActiveRecord::Base
      scope :inactive, lambda { |user_type|
        case user_type
        when 'v'
          where(some_condition_only_for_vendors)
        when 'c'
          where(different_condition_only_for_customers)
        else
          where(another_condition)
        end
      }
    
      def related_users
        User.inactive(user_type).all
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-25
      • 1970-01-01
      • 1970-01-01
      • 2019-08-27
      • 1970-01-01
      • 2019-08-23
      • 2014-10-26
      • 2016-05-28
      相关资源
      最近更新 更多