Best way to find_or_create_by_id but update the attributes if the record is found

前端 未结 7 1443
情书的邮戳
情书的邮戳 2021-01-06 03:50

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

7条回答
  •  星月不相逢
    2021-01-06 04:16

    You can write your own method:

    class ActiveRecord::Base
      def self.find_by_id_or_create(id, &block)
        obj = self.find_by_id( id ) || self.new
        yield obj
        obj.save
      end
    end
    

    usage

     Category.find_by_id_or_create(10) do |c|
       c.name = "My new name"
     end
    

    Of course, in this way you should extend method missing method and implement this method in the same way as others find_by_something methods. But for being short this will be enough.

提交回复
热议问题