DaniG2k
DaniG2k

Reputation: 4893

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!

Upvotes: 1

Views: 99

Answers (1)

zhisme
zhisme

Reputation: 2800

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

Upvotes: 1

Related Questions