简体   繁体   English

如何在Active Record模型上存储临时属性

[英]how to store temporary attributes on an Active Record model

I would like to store some debug messages on an object as it can go through processing but I don't want to be storing this to the database. 我想在对象上存储一些调试消息,因为它可以进行处理,但是我不想将其存储到数据库中。 Is something like this a reasonable way, an instance variable wrapped in a method with a nil guard? 像这样的合理方法吗,将实例变量包装在具有nil防护的方法中? Or is there a better way / pattern? 还是有更好的方法/模式?

class Bid < ApplicationRecord
  ...
  def debug_reasons
     @debug_reasons ||= []
  end
  ...

and then 接着

bid.debug_reasons << "here is a reason"

What you're looking for is attribute 您正在寻找的是attribute

class Bid < ApplicationRecord
  attribute :debug_reasons, :default => []
end

More info on attribute http://api.rubyonrails.org/v5.0/classes/ActiveRecord/Attributes/ClassMethods.html#method-i-attribute 有关attribute详细信息http://api.rubyonrails.org/v5.0/classes/ActiveRecord/Attributes/ClassMethods.html#method-i-attribute

For debugging purposes I would use logging with the appropriate log level. 出于调试目的,我将使用具有适当日志级别的日志记录。 This way the object behavior does not get messed up with the debugging. 这样,对象行为就不会与调试搞混了。

In addition, the debug log level can (should) be disabled in production environments, but adding logic inside your models will not make it so easy. 另外,可以(应该)在生产环境中禁用调试日志级别,但是在模型内部添加逻辑将使其变得不那么容易。

您可以使用本示例中的虚拟属性

I agree with Bustikiller that, for debugging purposes, logging the messages is a better option rather than changing your production code. 我同意Bustikiller的观点,出于调试目的,记录消息是比更改生产代码更好的选择。

But, If you really need it, I would use the ruby attr_accessor method rather than the ActiveRecord::Base.attribute method because the former doesn't expose an internal attribute as a model attribute. 但是,如果您确实需要它,我将使用ruby attr_accessor方法而不是ActiveRecord :: Base.attribute方法,因为前者不会将内部属性公开为模型属性。

The model attributes should be properties of the entity your model implements. 模型属性应该是您的模型实现的实体的属性。 A debug/internal method (such as #object_id and #to_s) should not be considered as an attribute and, therefore, they should not appear on attribute list (ie when you call #attributes on a model instance). 调试/内部方法(例如#object_id和#to_s)不应视为属性,因此,它们不应出现在属性列表中(即,在模型实例上调用#attributes时)。 By using the .attribute from ActiveRecord, you define debug_messages as an attribute of Bid which, I think, may not be an property of your Bid domain. 通过使用ActiveRecord的.attribute ,您可以将debug_messages定义为Bid的属性,我认为这可能不是您的Bid域的属性。

So, using the attr_accessor you don't pollute the ActiveModel API with an internal/logic attribute. 因此,使用attr_accessor不会污染具有内部/逻辑属性的ActiveModel API。

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

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