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

前端 未结 7 1484
情书的邮戳
情书的邮戳 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:58

    I did this yesterday, wishing there was a way to do it in a one-liner.

    Ended up going with (using your code):

    c = Category.find_or_initialize_by_id(category.id)
    c.name = category.name
    c.save
    

    Perhaps there is a nicer way, but this is what I used.

    [Edit: use initialize instead of create to avoid hitting the DB twice)

提交回复
热议问题