create_or_update method in rails

后端 未结 3 1713
-上瘾入骨i
-上瘾入骨i 2020-12-07 22:58
if ClassName.exists?([\"id = ?\", self.id])
  object = ClassName.find_by_name(self.name)
  object.update_attributes!( :street_address => self.street_address,
             


        
3条回答
  •  不知归路
    2020-12-07 23:50

    The checked answer above works well for Rails 3. That said the find_or_initialize_by_attribute methods were deprecated in Rails 4. This is the new way. See Rails4 Deprecation warning for find_or_initialize_by method

    person = Person.find_or_initialize(name: 'name')   
    person.update_attributes(other_attrs)
    

提交回复
热议问题