DmitryTsepelev / store_model

Work with JSON-backed attributes as ActiveRecord-ish models
MIT License
1.09k stars 89 forks source link

[QUESTION] How preserve data on update? #158

Closed rafaeldev closed 1 year ago

rafaeldev commented 1 year ago

I have an update context for user preferences which can be changed on differents pages:

Controller A

class ControllerA
def update
  User.update(settings_params)
end

private

def settings_params
  params.require(:user).permit(settings: [:function1])
end
end
class ControllerB
def update
  User.update(settings_params)
end

private

def settings_params
  params.require(:user).permit(settings: [:function2])
end
end

StoreModel

class UserPreferences
  include StoreModel::Model

  attribute :funciton1, :boolean, default: true
  attribute :funciton2, :boolean, default: true
end

When I call ControllerA passing function1 to be false and after calling ControllerB passing function2 to be false, function1 is updated to true.

I think so can I skip that working with #merge method... I need to know if it is a bad pattern on my side or if there is another alternative for this scenario

DmitryTsepelev commented 1 year ago

Hey hey, I think the problem is that this is a hash at the end of the day, and when you are setting it to either {function1: false} or {function2: false}, which makes the other field to be the default (true). You can fix that with .merge for sure and make things a bit more explicit.

Please let me know if it does not help and reopen the issue 🙂