在Rails 4中使用模型关联确定范围

时间:2014-02-28 06:21:06

标签: ruby-on-rails activerecord model-associations

有两种型号:折扣 TimeDiscount

折扣has_one TimeDiscount和TimeDiscount belongs_to折扣。

我需要将所有TimeDiscounts与关联的Discount.is_enabled等于true。我该怎么做?我知道范围界定,我可以做类似的事情:

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

请告诉我如何在这里使用协会。

3 个答案:

答案 0 :(得分:0)

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

这将返回符合您要求的TimeDiscount数组

答案 1 :(得分:0)

如下所示?

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

我相信这也可行:

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

(但我必须仔细检查一下)

答案 2 :(得分:0)

折扣模型中,

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

然后,获取启用折扣的TimeDiscount,

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

希望有所帮助:)