[英]How do I replace a belongs_to association without changing the original class
I have a class that looks like this: 我有一个看起来像这样的课程:
class Refinery::Blog::Post < ActiveRecord::Base
belongs_to :author, class_name: '::Refinery::User', foreign_key: :user_id
# SNIP very long class body
end
I don't want to override the whole class if I can help it, as there's a ton of behavior there that should remain intact, and many other parts of the engine reference the class by name so I can't subclass it. 如果我可以帮助它,我不想覆盖整个类,因为那里有大量的行为应该保持完整,引擎的许多其他部分按名称引用类,所以我不能将它子类化。 Is there any way using class_eval
to remove or replace an existing association? 有没有办法使用class_eval
来删除或替换现有的关联? I tried just redefining it like this: 我试着像这样重新定义它:
Refinery::Base::Post.class_eval do
belongs_to :author, class_name: 'MyUser', foreign_key: :user_id
end
but it doesn't seem to work. 但它似乎没有用。
Look in the initializer file, which I think is in config/initializers/refinery/blog.rb 查看初始化文件,我认为它位于config / initializers / refinery / blog.rb中
Refinery::Blog.configure do |config|
# If you're grafting onto an existing app, change this to your User class
Refinery::Blog.user_class = 'MyUser'
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.