![](/img/trans.png)
[英]Rails: Use constants from model for define instance methods into Concern
[英]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.