在rails中创建或更新记录

时间:2016-05-24 20:24:28

标签: ruby-on-rails-4 updating

我从外部数据库读取。 所以我做了这个,所以第一次运行代码就会创建数据库。 我只粘贴创建部分。来自外部数据库的读取是我不允许公开的代码。

Collection.create(
        name:         xxxxxx,
        title:        xxxxxx,
        description:  xxxxx,
        date:         xxxxx,
        collectie:    xxxxx,
        colors:       xxxxxx,
        small_image:  xxxxxx,
    )

如何更改此值,以便下次更新数据时数据已更改,因此我不必执行rake:drop and rake db:migrate,然后执行此rake任务,如果我想获取最新数据。

编辑1:我尝试更改为find_or_create,但后来我发现了很多错误

1 个答案:

答案 0 :(得分:0)

item = Collection.where(
    name:         xxxxxx,
    title:        xxxxxx,
    description:  xxxxx,
    date:         xxxxx,
    collectie:    xxxxx,
    colors:       xxxxxx,
    small_image:  xxxxxx
).first_or_create

然后,如果需要,您可以使用item.update操作项目。

相关问题