简体   繁体   中英

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? 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

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

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.

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.

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). 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.

So, using the attr_accessor you don't pollute the ActiveModel API with an internal/logic attribute.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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