In Rails, what is the best way to update a record or create a new one if it doesn't exist?

后端 未结 6 596
终归单人心
终归单人心 2020-12-24 07:14

I have a create statement for some models, but it’s creating a record within a join table regardless of whether the record already exists.

Here is what my code looks

6条回答
  •  独厮守ぢ
    2020-12-24 07:43

    my_class = ClassName.find_or_initialize_by_name(name)
    
    my_class.update_attributes({
       :street_address => self.street_address,
       :city_name => self.city_name,
       :zip_code => self.zip_code
    })
    

提交回复
热议问题