2016-02-03 4 views
1

у меня есть:Как определить область действия?

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)) 

ответ

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 
+1

Вы можете использовать обнаженные области, как что? –

+0

Решение 2 является ответом –

+0

Да, спасибо за вашу рекомендацию: D –

Смежные вопросы