Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create_or_update method in rails

if ClassName.exists?(["id = ?", self.id])
  object = ClassName.find_by_name(self.name)
  object.update_attributes!( :street_address => self.street_address,
    :city_name => self.city_name,
    :name => self.org_unit_name,
    :state_prov_id => self.state_prov_id,
    :zip_code => self.zip_code)
else
  ClassName.create! :street_address => self.street_address,
    :city_name => self.city_name,
    :federalid => self.federalid,
    :name => self.org_unit_name,
    :state_prov_id => self.state_prov_id,
    :zip_code => self.zip_code
end

I have code like this. I would like to improve it so that it uses a method, something like create_or_update.

    ClassName.create_or_update_by_name(:name => self.name,
    :street_address => self.street_address,
    :city_name => self.city_name,
    :federalid => self.federalid,
    :name => self.org_unit_name,
    :state_prov_id => self.state_prov_id,
    :zip_code => self.zip_code)

If the name exists in the database then it should update that object otherwise it should create a new object.

Is there is any method that exists that I can do this with?

like image 774
krunal shah Avatar asked Jun 11 '10 15:06

krunal shah


3 Answers

my_class = ClassName.find_or_initialize_by_name(name)

my_class.update_attributes(
   :street_address => self.street_address,
   :city_name => self.city_name,
   :federalid => self.federalid,
   :state_prov_id => self.state_prov_id,
   :zip_code => self.zip_code
)

As of Rails 6, update_attributes! and update_attributes is deprecated for update! and update, respectively:

my_class.update(
   :street_address => self.street_address,
   :city_name => self.city_name,
   :federalid => self.federalid,
   :state_prov_id => self.state_prov_id,
   :zip_code => self.zip_code
)
like image 86
Ju Nogueira Avatar answered Nov 17 '22 00:11

Ju Nogueira


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)
like image 28
Zach Colon Avatar answered Nov 16 '22 23:11

Zach Colon


person = Person.find_by_name(name) || Person.new(:name => name)
person.update_attributes!(:street_address => street_address, :city_name => city_name) #etc etc
like image 34
lambdabutz Avatar answered Nov 17 '22 00:11

lambdabutz