简体   繁体   English

在Rails中使用object_id列的含义

[英]Implications of Having an object_id Column in Rails

What are the implications of having a object_id / object_type on a model (for a polymorphic association) in regards to Object itself containing an object_id and that overriding it ( http://ruby-doc.org/core-2.3.1/Object.html#method-i-object_id )? 对于包含object_id并覆盖它的Object本身而言,在模型上(对于多态关联)具有object_id / object_type有什么含义( http://ruby-doc.org/core-2.3.1/Object。 html#method-i-object_id )?

class Event
  belongs_to :object, polymorphic: true # object_id/object_type
end

When I search for object_id through the whole codebase of one of my rails projects (including all gems), I can see over 200 hits. 当我通过我的一个rails项目(包括所有gem)的整个代码库搜索object_id ,我可以看到200多个点击。 In Rails only, this is about 50 hits . 仅在Rails中,这是大约50次点击

I'd expect problems with records comparison, using them as hash keys, putting them to set s, perhaps also duplicating them with dup . 我希望记录比较存在问题,将它们用作哈希键,将它们set s,或者也可以用dup 复制它们。 In Rails, record.object_id is referenced in caching, has_many_through associations, AREL, pretty printing the record, minitest expectations, also in pry debugger, 在Rails中, record.object_id在缓存, has_many_through关联,AREL,漂亮打印记录,minitest期望,也在pry调试器中引用,

But just from quick-looking trough the code it is very hard to guess if it will cause problems or not and I generally tend to be very defensive about such potential problems - you'll never know for sure if your next usage of the object will not break things in a way that is both very hard to debug and perhaps impossible to fix. 但是从快速查看代码来看,很难猜测它是否会导致问题而且我通常会对这些潜在问题保持警惕 - 你永远不会确定你下次使用该object是否会不要以一种既难以调试又可能无法修复的方式破坏事物。

As I said above, I'd be very curious if you tried, but myself would rather name it belongs_to :thing, polymorphic: true or better yet something even more specific. 正如我上面所说,如果你尝试过,我会很好奇,但我自己宁愿将它命名为belongs_to :thing, polymorphic: true或更好,但更具体的东西。

If you attempt to define object_id on a class you'll find that you get the following angry warning from the Ruby interpreter warning: redefining 'object_id' may cause serious problems (try it from IRB). 如果你试图在类上定义object_id ,你会发现你从Ruby解释器warning: redefining 'object_id' may cause serious problems得到以下生气warning: redefining 'object_id' may cause serious problems (从IRB尝试)。 That sounds scary - and the incidents may be tied to specific versions of Ruby (and vary based on the version used). 这听起来很可怕 - 事件可能与特定版本的Ruby绑定(并根据使用的版本而有所不同)。 I'd recommend fixing this. 我建议修理这个。

I believe you can belong_to object, while defining the foreign_key to something else, like foreign_key: :object_identifier. 我相信你可以将belongs_to对象,同时将foreign_key定义为其他东西,比如foreign_key :: object_identifier。 That way you dont have to worry about object_id. 这样你就不必担心object_id了。

我认为最好遵循本文档Active Record Associations ,我认为定义另一个object_id将使您在代码中手动维持关系,并且您将失去Active Record功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM