简体   繁体   中英

Rails: overwriting concern methods in the model

I am trying to have a basic set of methods across a number of models. To do that, I've extracted the methods to a concern. So:

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

However, it seems that the method defined in Userable is taking precedence over the has_many relation in the Broker class. So running something like broker.invoices returns #<ActiveRecord::Relation []> when I would actually want the has_many relation to take precedence. Is this feasible? Thanks in advance!

You can use defined? in your concern code to not override your scopes in 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM