【问题标题】:How do I replace a belongs_to association without changing the original class如何在不更改原始类的情况下替换 belongs_to 关联
【发布时间】:2013-07-24 13:15:15
【问题描述】:

我有一个如下所示的课程:

class Refinery::Blog::Post < ActiveRecord::Base
  belongs_to :author, class_name: '::Refinery::User', foreign_key: :user_id

  # SNIP very long class body
end

如果我能提供帮助,我不想重写整个类,因为那里有很多行为应该保持不变,并且引擎的许多其他部分通过名称引用该类,所以我不能子类化它.有什么方法可以使用class_eval 来删除或替换现有的关联?我试着像这样重新定义它:

Refinery::Base::Post.class_eval do
  belongs_to :author, class_name: 'MyUser', foreign_key: :user_id
end

但它似乎不起作用。

【问题讨论】:

  • 你能用 send 代替 class eval 看看它是否有效吗? class_eval 将在 rails 的 eigen 类上下文中评估该代码。

标签: ruby-on-rails ruby metaprogramming rails-activerecord refinerycms


【解决方案1】:

查看初始化文件,我认为它在 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

【讨论】:

  • 不走运。该选项在 git repo 中,但不在最新版本(当前为 2.0.4)中。
  • 嗯。看起来添加更改的提交相当小;能补一下吗?
猜你喜欢
  • 2020-11-05
  • 1970-01-01
  • 2017-08-18
  • 1970-01-01
  • 2019-10-26
  • 2012-07-01
  • 1970-01-01
  • 2020-08-04
  • 2021-06-09
相关资源
最近更新 更多