ruby-association中的Dynaimc class_name

时间:2021-02-13 10:57:18

Problem
There are some models which should be copied as a template.
For example: There is a News entry and I want to copy it to several groups.
So the copied elements should have the association to the template. And the template should have an association to it's elements.

问题有些模型应该作为模板复制。例如:有一个新闻条目,我想将其复制到几个组。因此复制的元素应该与模板有关联。模板应该与它的元素有关联。

Current State
Because there are several models with the same methods as a copyable element, I've created a concern. I've tried a dynamic association name to link to itself's class but when I create an element, there is a Missmatch Error.

当前状态因为有几个模型使用与可复制元素相同的方法,所以我创建了一个问题。我已经尝试了一个动态的关联名称来链接到自己的类,但是当我创建一个元素时,会出现一个Missmatch错误。

item = self.class.find_or_create_by(group: group, group_template: self)
ActiveRecord::AssociationTypeMismatch: Class(#18118120) expected, got News(#140451780)

The association in the concern

该关联在关注中

included do
  belongs_to :business_group
  belongs_to :group_template, class_name: self.class.name, foreign_key: :template_id
  has_many :group_elements, class_name: self.class.name, foreign_key: :template_id
end

Is there a dynamic solution or should I remove it from the concern and copy it to all models?

是否存在动态解决方案,还是应该将其从关注点中删除并将其复制到所有模型中?

1 个解决方案

#1


1  

In your included block self is the class being included into. self.class_name is probably what you want. self.class.class_name is what you have and is asking for the class of a model class, which is Class.

在您的包含块中,self是包含在其中的类。 self.class_name可能就是你想要的。 self.class.class_name就是你所拥有的,并且要求模型类的类,即Class。

The only time you really should use self.class is when you are in the scope of an instance of a class and need to access the class of that instance object. In your included block you are already in the class context so .class is asking for the class of a class.

你真正应该使用self.class的唯一一次是当你在一个类的实例范围内并且需要访问该实例对象的类时。在您包含的块中,您已经在类上下文中,因此.class要求类的类。

Meta-programming can get kind of confusing. Hope that makes sense.

元编程可能会让人感到困惑。希望有道理。

#1


1  

In your included block self is the class being included into. self.class_name is probably what you want. self.class.class_name is what you have and is asking for the class of a model class, which is Class.

在您的包含块中,self是包含在其中的类。 self.class_name可能就是你想要的。 self.class.class_name就是你所拥有的,并且要求模型类的类,即Class。

The only time you really should use self.class is when you are in the scope of an instance of a class and need to access the class of that instance object. In your included block you are already in the class context so .class is asking for the class of a class.

你真正应该使用self.class的唯一一次是当你在一个类的实例范围内并且需要访问该实例对象的类时。在您包含的块中,您已经在类上下文中,因此.class要求类的类。

Meta-programming can get kind of confusing. Hope that makes sense.

元编程可能会让人感到困惑。希望有道理。