2015-11-07 112 views
0

我想爲特定用戶獲取「offer」類型的所有TaskInteractions。Rails:如何結合關聯和範圍

我有一個用戶模型

has_many :task_interactions 

和TaskInteraction模型

belongs_to :user 

TaskInteraction具有屬性 「類型」,它的值可以是提供或測驗。

目前,我使用範圍

scope :offer_interactions, -> { where(type: 'offer') } 

而我得到的結果

@user.task_interactions.offer_interactions 

或用戶模式,我可以定義:

def offer_interactions 
    self.task_interactions.where(type: 'offer') 
end 

或者,如果我結合範圍和offer_interactions方法:

def offer_interactions 
    self.task_interactions.offer_interactions 
end 

問題:

有沒有更好的方式來獲得這個結果?

有沒有Rails方式解決這個問題?

回答

2

您還可以添加在用戶模型中的作用域has_many關係,只考慮到報價task_interactions:

has_many :offer_interactions, -> { where(type: 'offer') }, class_name: 'TaskInteraction'

然後就叫@user.offer_interactions

+0

謝謝,這就是我一直在尋找對於。 – Randomtheories