【问题标题】:Intercept has_many association call拦截 has_many 关联调用
【发布时间】:2016-09-19 15:08:53
【问题描述】:

有两种型号

class Order < ...
  has_many :products
  def products
    products.count.zero? ? <some action> : products  
  end
end

class Product < ...
end

我需要在订单上拦截产品调用:Order.first.products 以在没有产品的情况下用一些自定义逻辑替换输出,或者在有产品的情况下返回相关产品。 我试过 read_attribute 但没有成功。

【问题讨论】:

  • 你为什么不写一个新的方法来做到这一点
  • 因为在这种情况下我应该在很多地方替换产品关联调用。我不想那样做。

标签: ruby-on-rails activerecord associations


【解决方案1】:

您可以简单地扩展或覆盖您需要的任何方法:

class Order < ActiveRecord::Base
  def products
    my_logic || super
  end
end

【讨论】:

    猜你喜欢
    • 2021-10-14
    • 1970-01-01
    • 2011-07-13
    • 1970-01-01
    • 1970-01-01
    • 2015-04-16
    • 1970-01-01
    • 2017-07-19
    相关资源
    最近更新 更多