Ruby-on-rails rails 中的 create_or_update 方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3024010/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 22:45:51  来源:igfitidea点击:

create_or_update method in rails

ruby-on-railsruby

提问by krunal shah

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.

我有这样的代码。我想改进它,以便它使用一种方法,例如 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 nameexists in the database then it should update that object otherwise it should create a new object.

如果name存在于数据库中,那么它应该更新该对象,否则它应该创建一个新对象。

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

有没有什么方法可以让我做到这一点?

回答by Ju Nogueira

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
)

回答by Zach Colon

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

上面的检查答案适用于 Rails 3。也就是说find_or_initialize_by_attribute,Rails 4 中不推荐使用这些方法。这是新方法。有关find_or_initialize_by 方法,请参阅Rails4 弃用警告

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

回答by lambdabutz

person = Person.find_by_name(name) || Person.new(:name => name)
person.update_attributes!(:street_address => street_address, :city_name => city_name) #etc etc