【问题标题】:Scoping with Model association in Rails 4Rails 4 中的模型关联范围
【发布时间】:2014-02-28 06:21:05
【问题描述】:

有两种模式:DiscountTimeDiscount

折扣has_oneTimeDiscount 和TimeDiscount belongs_to 折扣。

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

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

请在这里告诉我如何使用关联。

【问题讨论】:

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


【解决方案1】:
Discount.where(is_enabled: true).map do |discount|
  discount.time_discounts
end

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

【讨论】:

  • 为了更好的性能和更简洁,你可以使用Discount.includes(:time_discount).where(is_enabled: true).map(&:time_discounts).flatten
【解决方案2】:

类似以下内容?

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

我相信这也可能有效:

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

(但我必须仔细检查那个)

【讨论】:

    【解决方案3】:

    折扣模式中,

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

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

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

    希望对你有帮助:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-23
      • 1970-01-01
      • 2017-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-07
      • 1970-01-01
      相关资源
      最近更新 更多