I have a User.rb model and a UserSetting.rb model that i would like to delegate to (both getter and setter methods).
in user.rb
delegate :email_opt_in, :email_opt_in=, :to => :user_setting
At first glance this works great.
user = User.find(1)
user.email_opt_in #=> false
user.email_opt_in = true
user.save
user.email_opt_in #=> true
But looking closer the, user.save doesn’t propagate to the UserSetting model.
User.find(1).email_opt_in #=> false
(So the value didn’t get saved to the database).
This is my question: How can I get UserSetting to save automatically when one of its attributes are changed and then saved by its user?
This should only happen when a UserSetting attribute is changed otherwise every time a user is saved to the database it will trigger an additional un-needed & unwanted write to the database.
I would explore using an ActiveRecord callback for this. I’m not sure which would make the most sense in your case, but
before_updateorafter_updateseem logical. In your callback, you would need to manually trigger a save call on the UserSetting object associated with the User. There’s probably dozens of ways to accomplish this, but something along these lines should work: