I want to give Rails models common treatment

Asked 2 years ago, Updated 2 years ago, 28 views

class User<<ActibeRecord::Base

  json_column:data

end

class Post <<ActibeRecord::Base

  json_column —info

end

By specifying the columns for each model in this way, I want to be able to add processing before saving and when referring to the values, but I don't know how to do it.

class ActiveRecord::Base
  before_save —before
  after_find —After

  private

  def before
    # Cast the value specified by json_column into a string
  end

  after
    # JSON.parse the value specified in json_column
  end
end

This is an image that moves by installing something like this in raols_root/config/initializers/json_column.rb.
If this is the case, I think I can implement it if I only know how to get the value specified in json_column.

Also, what is the name of this json_column?
I'm at a loss because I don't know how to check.

I would appreciate it if you could tell me the sample source and reference site.
Thank you for your cooperation.

*This time, I used json as an example for easy understanding, but the actual action I want to take is different.

ruby-on-rails ruby

2022-09-29 22:11

2 Answers

What about class_attribute

class ApplicationRecord <ActiveRecord::Base
  self.abstract_class = true
  class_attribute —json_column
  before_save —before

  private

  def before
    p [self.class.json_column, self [json_column]]
  end
end

class User<ApplicationRecord
  self.json_column=:data
end

class Post <ApplicationRecord
  self.json_column= —info
end

User.create (data: 'xxx')
Post.create (info: 'yyyy')


2022-09-29 22:11

If you want to do this by hooking the timing of validation, saving it to the database, etc.

Active Record Callback https://railsguides.jp/active_record_callbacks.html

If you want to detect a change in the model value

Active Model Dirty Module
https://railsguides.jp/active_model_basics.html#dirty%E3%83%A2%E3%82%B8%E3%83%A5%E3%83%BC%E3%83%AB


2022-09-29 22:11

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.