rog*_*rkk 4 ruby activerecord ruby-on-rails rails-activerecord activesupport-concern
我有一个关注点来设置一些常用的关联(除其他外),但我需要根据使用关注点的类进行一些小的调整。我的基本担忧是这样的:
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
```
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,我希望能够更改组织关联中的类名称。
我想我可以包含一些类方法来提供这种支持,但我无法弄清楚如何继续获取这个值。以下是我对自己使用它的看法:
class Dentist < Person
include Organizable
organizable organization_class: DentistClinic
end
Run Code Online (Sandbox Code Playgroud)
这是我当前版本的代码:
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
Run Code Online (Sandbox Code Playgroud)
我认为这至少存在两个问题:
1)该.organization_class方法似乎没有在建立关联时定义,因为NoMethodError: undefined method当我加载牙医模型时,我得到了 Class:Class` 的organization_class'。
2)我猜想在我将类传递给关注点(行organizable organization_class: DentistClinic)之前,关注点内的关联将被评估,所以它无论如何都不会包含值。
我真的不确定如何解决这个问题。有没有办法将此参数传递到关注点并使用该值设置关联?
这不是如何创建带有参数的 Rails 4 Concern的重复
我正在做的事情几乎完全符合那篇文章中概述的内容。我的用例有所不同,因为我尝试使用参数来配置在关注点内定义的关联。
我遇到了类似的问题,我需要根据模型本身的参数在关注点内定义自定义关联。
我找到的解决方案(在 Rails 5.2 中测试过,但其他版本应该类似)是在类方法内定义关系,类似于 Mirza 建议的答案。
以下是代码示例“The Concern”:
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
Run Code Online (Sandbox Code Playgroud)
该模型:
class Dentist < Person
include Organizable
organization_class_name DentistClinic
end
Run Code Online (Sandbox Code Playgroud)
我也更愿意完全按照您在答案中建议的方式进行操作,看起来更干净,但这需要在之前评估和使用类方法included do。
基本上我需要的是一种在关联定义中使用关注参数的方法,这是最直接的方法,如果有人需要它,我将其留在这里。