Ruby Object#id 警告和 Active Record
当我们运行规范时,我们不断看到如下警告:
Object#id 将被弃用; 使用对象#object_id
相关代码正在访问 ActiveRecord 模型的 id(显然,这是表上的一个属性,而不是 Ruby VM 中的对象实例 ID)。
有谁知道如何关闭这些特定警告或以某种方式避免它们?
We keep seeing warnings like the following when we run our specs:
Object#id will be deprecated; use Object#object_id
The code in question is accessing the id of an ActiveRecord model (which is an attribute on the table, obviously, rather than the object instance ID in the Ruby VM).
Does anyone know how to turn these particular warnings off or somehow avoid them?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
尝试使用
[:id]
而不是.id
Try using
[:id]
instead of.id
当对象从
ActiveRecord::Base
派生时,对id
的调用将转到 AR::B 的id
方法,而不是已弃用的方法对象
。该警告通常意味着我的一个对象不是我想象的那样。
When an object is descended from
ActiveRecord::Base
, a call toid
goes to AR::B'sid
method rather than the deprecated one onObject
.That warning usually means one of my objects isn't what I think it is.
object#id 警告仅发生在常规 ruby 类(如 NilClass)上。 ActiveRecord::Base 覆盖 object#id
The object#id warning only happen on regular ruby classes like NilClass. ActiveRecord::Base overrides object#id
您的对象实际上并不是 AR 对象,通常表明某些数据检索失败(
Table.find_by_name('nonexistent name')
将返回nil
)。 如果您只想关闭可见警告,则可以在配置中关闭whiny_nils
,否则在尝试访问对象的属性之前执行is_a?
测试优雅地处理失败案例。Your object is not actually an AR object, usually indicating that some data retrieval has failed (
Table.find_by_name('nonexistent name')
will returnnil
). If all you want to do is shut off the visible warnings, you can turn offwhiny_nils
in your config, otherwise do anis_a?
test before trying to access the object's attributes and handle the failure case gracefully.我假设您正在进行模拟/存根(因为您提到了规格)。
就我而言,当我存根 ActiveRecord 对象并访问其 ID 属性时,我遇到了这些警告。
如果您希望访问 ActiveRecord 对象的 ID,我建议您执行以下操作:
I'm assuming you're doing mocking / stubbing (because you mentioned specs).
In my case, I run into these warnings when I stub an ActiveRecord object and access its ID attribute.
In cases where you expect to access the ID of your ActiveRecord object, I'd recommend you do the following: