gpt4 book ai didi

ruby-on-rails - 如何在所有模型上添加 has_many 关联

转载 作者:太空宇宙 更新时间:2023-11-03 17:27:54 25 4
gpt4 key购买 nike

现在我有一个初始化程序可以执行此操作:

ActiveRecord::Base.send :has_many, :notes, :as => :notableActiveRecord::Base.send :accepts_nested_attributes_for, :notes

它很好地建立了关联,除了当我加载一个使用它的 View 时,第二次加载给了我:不能复制 NilClass来自:

/usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:2184:in `dup'
/usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:2184:in `scoped_methods'
/usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:2188:in `current_scoped_methods'
/usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:2171:in `scoped?'
/usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:2439:in `send'
/usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:2439:in `initialize'
/usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/reflection.rb:162:in `new'
/usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/reflection.rb:162:in `build_association'
/usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/associations/association_collection.rb:423:in `build_record'
/usr/lib/ruby/gems/1.8/gems/activerecord-2.3.5/lib/active_record/associations/association_collection.rb:102:in `build'
(my app)/controllers/manifests_controller.rb:21:in `show'

有什么想法吗?我做错了吗?有趣的是,如果我将关联移动到我正在使用的模型上,我不会收到此错误。我想我一定是错误地建立了全局协会。

最佳答案

您声明您有很多模型,所有模型都需要这种关联。如果是我,我会采用创建包含关联的基本模型类的方法,然后让所有其他模型继承它。像这样的东西:

class NotableModel < ActiveRecord::Base

# Prevents ActiveRecord from looking for a database table for this class
self.abstract_class = true

has_many :notes, :as => :notable
accepts_nested_attributes_for :notes
end

class Foo < NotableModel
...
end

class Bar < NotableModel
...
end

在我看来,与使用隐藏在初始化程序中的一点点元编程相比,这种方法更易于 self 记录。

关于ruby-on-rails - 如何在所有模型上添加 has_many 关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2691326/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com