检查具有关联的对象 [英] Inspect object with associations

查看:76
本文介绍了检查具有关联的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个模型,其中A has_manyB.如果我这样加载包括关联B的A:

I have two models where A has_many B. If I load A including associated B as such:

a = A.find(:first, include: :bs)

a.inspect仅显示a的属性:

 => "#<A id: 1, name: \"Test\", created_at: \"2012-07-02 21:50:32\", updated_at: \"2012-07-02 21:50:32\">"

我该如何做a.inspect以使其显示所有关联的a.bs?

How can I do a.inspect such that it displays all associated a.bs?

推荐答案

默认情况下,您不能执行此操作.检查对象可能会产生太多问题和副作用.但是,您可以使用以下内容扩展inspect自己:

You can't do that by default. It might create too many problems and side effects with inspecting objects. However you could extend inspect yourself with something like this:

class A < ActiveRecord::Base
  ...
  def inspect
    [super, bs.inspect].join("\n")
  end
end

请注意,这并不是很聪明,因为它会在您每次检查A实例时强制加载bs.所以也许你想变得更聪明,做这样的事情:

Note though that that's not very clever, since it will force the loading of bs every time you inspect an A instance. So maybe you want to be smarter and do something like this:

def inspect
  [super, bs.loaded? ? bs.inspect : nil].compact.join("\n")
end

这只会检查bs是否已经预加载(例如,:include).

This will only inspect bs if it's already preloaded (with :include for example).

或者您可能想创建一个super_inspect而不是自动执行所有操作.您可以使用以下内容扩展ActiveRecord::Base:

Or maybe you want to create a super_inspect instead that does everything automatically. You could extend ActiveRecord::Base with something like:

class ActiveRecord::Base
  def deep_inspect
    ([inspect] + self.class.reflect_on_all_associations.map { |a|
      self.send(a.name).inspect
    }).compact.join("\n  ")
  end
end

这将自动使用查找所有关联reflect_on_all_associations ,如果该关联已加载,它将在其上调用inspect.

现在,您可以修改上面的代码,但是要创建自己的自定义检查,或者根据需要扩展当前检查.一点点代码,一切皆有可能.

Now you can modify the above code however you want to create your own customized inspect, or just extend the current inspect if you like. Anything is possible with a little bit of code.

以下是更聪明的更新版本的示例:

Here is an example of an updated version that is a bit smarter:

class ActiveRecord::Base
  def deep_inspect
    ([inspect] + self.class.reflect_on_all_associations.map { |a|
      out = ""
      assoc = self.send(a.name)
      # Check for collection
      if assoc.is_a?(ActiveRecord::Associations::CollectionProxy)
        # Include name of collection in output
        out += "\n#{assoc.name.pluralize}:\n"
        out += self.send(a.name).to_a.inspect
      else
        out += self.send(a.name).inspect
      end
      out
    }).compact.join("\n  ")
  end
end

这篇关于检查具有关联的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆