2014-02-28 74 views
2

有兩種模式:折扣時間折扣範圍與模型協會在軌道4

折扣has_one TimeDiscount和TimeDiscount belongs_to折扣。

我需要得到所有TimeDiscounts與關聯Discount.is_enabled等於true。我該怎麼做?我知道關於範圍,我可以做類似於這件事:

scope :new_orders, -> { where(order_status: OrderStatus.new_order) } 

請告訴我如何利用這裏的關聯。

+0

http://stackoverflow.com/questions/5874118/scope-with-joins-to-get-data-in-rails-3 – emaillenin

+0

你得到你的答案? –

回答

0
Discount.where(is_enabled: true).map do |discount| 
    discount.time_discounts 
end 

這將返回TimeDiscount匹配您的要求

+0

雖然不完全表現。 – sevenseacat

+0

爲了獲得更好的性能,並且要更簡潔一些,可以使用Discount.includes(:time_discount).where(is_enabled:true).map(&:time_discounts).flatten' – jvperrin

0

像下面這樣的數組?

TimeDiscount.includes(:discount).where(discount: {is_enabled: true}) 

我相信這也可能工作:

TimeDiscount.includes(:discount).merge(Discount.is_enabled) 

(但我將不得不仔細檢查一個)

0

折扣型號,

scope :Active_Orders, -> { where(is_enabled: true) } 

然後,獲取啓用折扣的TimeDiscount,

@Active_TimeDiscounts = Discount.Active_Orders.map{|active_ord| active_ord.TimeDiscount} 

希望它能幫助:)