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

前端 未结 7 1439
情书的邮戳
情书的邮戳 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 03:56

    I liked fl00r's answer. But why do we have to save the object every time? We can check if its already there in records or else save it

    def self.find_or_create_by_id(id, &block)
        obj = self.find_by_id(id) 
        unless obj
          obj = self.create(id: id)
        end
        obj
    end
    

提交回复
热议问题