PaperTrial versions handling changeset error

224 views Asked by At

here are my models looks like so I can address properly my issue

class Product

  has_paper_trail
  
  belongs_to :category

end

On my HTML side, I need to load all the logs using the PaperTrial versions. like this

@product.versions.each |version|
 version.changeset.each do |k, v|
   - if k.to_s == "category_id"
    - old_record = v[0].blank? ? " No Record " : Category.find(v[0].to_i).name
    - new_record = v[1].blank? ? " No Record " : Category.find(v[1].to_i).name
    = "Category" + " From: " + "#{old_record} " + " To: " + "#{new_record}"
 

in my HTML looks fine but. there is a scenario. that category will be deleted. and I will get an error in this view. because of my "Category.find". the find method cant find the Category that already deleted.

is there a way to store the name of the category and not the ID. so I can get rid of using "find"

or there is a better way to implement these things?

1

There are 1 answers

3
DonPaulie On

I'd recommend adding category_name attribute to your product model for caching.

# migration
rails g migration AddCategoryNameToProducts category_name

# Product model
  before_validation :cache_category_name
  def cache_category_name
    self.category_name = category&.name if category_name != category&.name
  end

But if you had already gone production, you must fill in the data first. And you are not able to fill data, that is already deleted.

# console or migration
Category.find_each(&:save!)

This scenario preserves the deleted category name, additionally it will be much more efficient than a lot of Category.find.

Or you can do some kind of soft-delete as others suggested.