create_or_update method in rails
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
)
person = Person.find_by_name(name) || Person.new(:name => name)
person.update_attributes!(:street_address => street_address, :city_name => city_name) #etc etc
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)