Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
385 views
in Technique[技术] by (71.8m points)

ruby - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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
)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...