簡體   English   中英

Rails:覆蓋 model 中的關注方法

[英]Rails: overwriting concern methods in the model

我正在嘗試在多個模型中使用一組基本方法。 為此,我已將方法提取到關注點。 所以:

module Userable
  extend ActiveSupport::Concern

  def invoices
    Invoice.none
  end
end

class Agent < ApplicationRecord
  include Userable
end

class Broker < ApplicationRecord
  include Userable

  has_many :invoices
end

但是,似乎Userable中定義的方法優先於Broker class 中的has_many關系。 因此,當我實際上希望has_many關系優先時,運行類似broker.invoices的東西會返回#<ActiveRecord::Relation []> 這可行嗎? 提前致謝!

你可以用defined? 在您的concern代碼中不要覆蓋 model 中的范圍。

module Userable
  extend ActiveSupport::Concern

  unless defined? :invoices
    def invoices
      Invoice.none
    end
  end
end

Broker.invoices.count
# => # real count e.g. 10

Agent.invoices.count
# => 0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM