简体   繁体   English

如何在不更改原始类的情况下替换belongs_to关联

[英]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.

相关问题 如何在没有直接belongs_to的情况下设置一种“belongs_to:through”关联? - How do I set up a kind of “belongs_to :through” association without a direct belongs_to? 我如何为belongs_to 关联播种? - How do I seed a belongs_to association? 所属协会-我怎么称呼它? - belongs_to association — how do I call it? 我如何使用searchlogic来搜索一个Emirates_to关联? - How do I use searchlogic to search on a belongs_to association? 迁移以更改belongs_to关联 - Migration for changing belongs_to association 我是否需要检查 Rails 中的belongs_to 关联中是否存在记录? - Do I need to check if record exist in a belongs_to association in Rails? 在Rails中,如何在不经过数据库的情况下检索上属居所关联上的对象? - In Rails, how can I retrieve the object on a belongs_to association, without going through the database? 在Rails 5.1 中,如何为has_many 和belongs_to 关联编写finder 方法? - In Rails 5.1, how do I write a finder method for a has_many and then belongs_to association? 如何在Rails 4.2中创建一个名为has_many和belongs_to的关联? - How do I create a named has_many and belongs_to association in Rails 4.2? 当关联对象被销毁时,如何将belongs_to关联设置为Nil - How do I set a belongs_to association to Nil when the associated object is destroyed
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM