如何定义范围?

时间:2016-02-03 10:38:03

标签: ruby-on-rails

我有:

price_plan.rb

class PricePlan < ActiveRecord::Base
  has_many :users
  scope :premium, lambda { where('price > ?', 0) }
  scope :free, lambda { where('price == ?', 0) }
end

user.rb

class User < ActiveRecord::Base
  belongs_to :price_plan
  has_one :account
  scope :free, lambda { joins(PricePlan.free) } #<--- no!
end

如何为免费使用服务的用户定义范围? 下面的内容应该有效,但我不喜欢它。

scope :free,-> where(priceplan_id: PricePlan.free.pluck(:id))

1 个答案:

答案 0 :(得分:2)

将是

解决方案1 ​​:对关系使用条件

class User < ActiveRecord::Base
  # Your current code
  belongs_to :free_price_plan, -> { free }, class_name: 'PricePlan'
  belongs_to :premium_price_plan, -> { premium }, class_name: 'PricePlan'
end

解决方案2 :定义范围

class User < ActiveRecord::Base
  # Your current code
  scope :free, -> {
    joins(:price_plan).merge(PricePlan.free)
  }

  scope :premium, -> {
    joins(:price_plan).merge(PricePlan.premium)
  }
end