I\'m looking for a clean way to create a record with a set of attributes if the record does not exist and - if the record do exist - to update its attributes. I love the syn
I think the simplest way is using Ruby's tap method, like this:
Category.find_or_initialize_by(id: category.id).tap do |c|
c.name = category.name
c.save
end
Also, I changed find_or_create_by_id
to find_or_initialize_by
, otherwise it will hit the database twice.
find_or_initialize_by
finds or intitializes a record, then returns it. We then tap into it, make our updates and save it to the database.