【问题标题】:Does model_name.new() in ActiveRecord create only new records or update existing as wellActiveRecord 中的 model_name.new() 是否只创建新记录或更新现有记录
【发布时间】:2013-04-10 15:56:32
【问题描述】:

我有一个模型,我在下面的 ruby​​ 脚本中使用了活动记录。诸如 level_type、name、parent.id 和 pipcode 之类的内容被分配给模型的属性,以便进入级别表。我的问题是,这仅适用于新记录吗?您会看到,名称、parent.id 和 pipcode 经常更改。我不希望它在每次这些值更改时创建新记录。我希望它使用来自 pipcode、parent.id 等的新值更新现有记录。

我的记录创建代码:

          new_region = Level.new(
            :level => level_type,
            :name => name,
            :parent_id => parent.id,
            :make_code => pipcode
          )

【问题讨论】:

    标签: ruby-on-rails ruby activerecord rake pg


    【解决方案1】:

    Level.new(...) 通常用于在调用 new_region.save() 时创建新行

    如果你想更新,首先你需要通过调用类似的方法找到你想更新的行:

    # if patient_id is the primary key
    existing_region = Level.find(patient_id)
    

    此时可以更新existing_region的参数,调用.save()更新数据库。

    existing_region.level = level_type
    existing_region.name = name
    ...
    existing_region.save()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-12
      • 2012-07-25
      • 2021-03-30
      • 2013-09-25
      • 2011-12-10
      • 1970-01-01
      • 2020-06-20
      相关资源
      最近更新 更多