[ActiveModel] assign_attributes and return self

I often add a method like this to ApplicationRecord for chaining method calls on top of assign_attributes by returning self.

def merge_attributes(new_attributes)



I find it useful to cut out single line assign_attributes calls.

@some_model = SomeModel.find_or_initialize_by(uuid: permitted_params[:uuid]).merge_attributes(permitted_params)

if @some_model.save




some_collection.map { |some_model_instance| some_model_instance.merge_attributes(some_attributes) }


I kind of want this to be how assign_attributes behaves by default, and allow the currently aliased attributes= to do what assign_attributes currently does. Right now there isn’t a useful return value like you would get with ‘create’ or ‘new’.

merge_attributes kind of captures the behavior and the way I use this but I am definitely open to guidance on naming and I am very interested in hearing if anyone else finds this useful. It is not a big deal for me to continue to implement ad hoc the way I have been on top of existing functionality but I’d be happy to put up a PR if there is interest in including this in Rails itself.

Thank You.

I would find this incredibly useful. I write code similar to what was described frequently. In fact, earlier today I wrote this snippet:

def fetch_end_user(data)
end_user = application.end_users.find_or_initialize_by(external_id: data[:user_id])
end_user.attributes = data.slice(*permitted_end_user_attributes)