我有一个关注点来设置一些常用的关联(除其他外),但我需要根据使用关注点的类进行一些小的调整。我的基本关注点如下:
module Organizable
extend ActiveSupport::Concern
included do
has_many :person_organizations
has_many :organizations,
through: :person_organizations,
class_name: <STI CLASS NAME HERE>
end
end
```
如您所见,我希望能够更改组织关联中的类名。
我想我可以包括一些类方法来提供这种支持,但我无法弄清楚我们如何继续获取这个值。以下是我对自己使用它的看法:
class Dentist < Person
include Organizable
organizable organization_class: DentistClinic
end
这是我当前的代码版本:
module Organizable
extend ActiveSupport::Concern
module ClassMethods
attr_reader :organization_class
private
def organizable(organization_class:)
@organization_class = organization_class
end
end
included do
has_many :person_organizations
has_many :organizations,
through: :person_organizations,
class_name: self.class.organization_class.name
end
end
我认为这至少有两个问题:
1) .organization_class
方法在关联建立时似乎没有定义,因为我得到一个 NoMethodError: undefined method
organization_class ' 加载 Dentist 模型时的 Class:Class`。
2) 我想在我什至将类传递给关注点之前,关注点内部的关联将被评估(organizable organization_class: DentistClinic
行),所以它无论如何都不包含值.
我真的不确定如何解决这个问题。有没有办法将此参数传递给关注点并使用此值设置关联?
这不是 How to create a Rails 4 Concern that takes an argument 的副本
我正在做 与那篇文章中概述的几乎完全相同。我的用例不同,因为我试图使用参数来配置在关注点内定义的关联。
最佳答案
我遇到了类似的问题,我需要根据模型本身的参数在关注点内定义自定义关联。
我找到的解决方案(在 Rails 5.2 中测试过,但其他版本应该类似)是在类方法中定义关系,类似于 Mirza 建议的答案。
这是代码示例, 关注点:
require 'active_support/concern'
module Organizable
extend ActiveSupport::Concern
included do
has_many :person_organizations
end
class_methods do
def organization_class_name(class_name)
has_many :organizations,
through: :person_organizations,
class_name: class_name
end
end
end
模型:
class Dentist < Person
include Organizable
organization_class_name DentistClinic
end
我也更愿意完全按照您在回答中建议的那样做,看起来更干净,但这需要在 included do
之前评估和使用类方法。
基本上我需要的是一种在关联定义中使用关注参数的方法,这是最直接的方法,如果有人需要,我会把它留在这里。
关于ruby-on-rails - 将参数传递给关注点,联合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37895643/