Rails&ActiveRecord 4.2.1,Ruby 2.2.0
编辑:请注意这个问题主要是讨论ActiveRecord的反射方面是如何工作的,以便更好地理解AR和Rails .
我正在研究一个关注ActiveRecord模型的关联,并根据这些关联创建回调 . 通过对单个文件或示例的测试 . 但是,在测试完整套件或运行开发服务器时,它会失败,因为某些模型返回nil进行反射 . 要旨:
module CustomActivityMaker
extend ActiveSupport::Concern
module ClassMethods
# @param {Array[Symbols]} assns
# 'assns' params is a list of a model's associations
def create_activity_for(assns)
assns.each do |assn|
r = self.reflect_on_association(assn)
if r.is_a?(ActiveRecord::Reflection::ThroughReflection)
# For a through association, we just track the creation of the join table.
# byebug
r.source_reflection.klass # <== source_reflection unexpectedly ends up being nil
else
r.klass
end
...
end
end
end
end
像这样调用:
# models/contact.rb
class Contact < ActiveRecord::Base
has_many :emails
has_many :addresses
has_many :phone_numbers
has_many :checklists
has_many :checklist_items, through: :checklists
create_activity_for :checklist_items
...
end
# models/checklist.rb
class Checklist < ActiveRecord::Base
belongs_to :contact
has_many :checklist_items
...
end
# models/checklist_item.rb
class ChecklistItem < ActiveRecord::Base
belongs_to :checklist
has_one :matter, through: :checklist
...
end
该错误显示在CustomActivityMaker的注释说明中 . 使用byebug时,变量r是ActiveRecord :: Reflection :: ThroughReflection . 对source_reflection的调用应该是一个ActiveRecord :: Reflection :: HasManyReflection,'klass'给我ChecklistItem类 .
但是:source_reflection出现了nil . 使用byebug检查错误,通过类清单没有任何反射:
Checklist.reflections # <== {}
当然,如果我在控制台中进行检查或运行单独测试时,这不是结果 .
我不了解Rails加载过程,以及它如何以及何时构建ActiveRecord反射,以及何时以及如何可靠地访问它们 . 任何见解?
1 回答
我无法't find any resources to guide me through Rails'内部工作,所以我去看一个流行的宝石,同样需要解析通过ActiveRecord :: Reflections,ActiveModel::Serializer,因为它也可能不得不处理Rails没有按照自己的意愿加载东西 . 在那里,我found:
添加到我的关注解决了我的问题 . 来自ActiveSupport :: Autoload docs:"This module allows you to define autoloads based on Rails conventions (i.e. no need to define the path it is automatically guessed based on the filename) and also define a set of constants that needs to be eager loaded" .