ruby-on-rails - first_or_create 只插入

标签 ruby-on-rails ruby if-statement

我在 Rails 5.2 项目中使用以下代码:

c = Country.where(name: "test").first_or_create

c.status = "Old"
c.save

这行得通,但是,我只想在还没有国家时更改状态(所以我只想插入国家,而不是更新)。但是,我还需要稍后在我的代码中使用 c

我意识到我可以只做一个 if 语句,但我必须在我的代码中多次做类似的事情,而且似乎必须存在一个捷径。

最佳答案

使用create_with通过以下:

c = Country.create_with(status: 'old').find_or_create_by(name: 'test')

这将创建 Countrystatus 'old'name 'test' 只有当它没有找到名称为 'test' 的国家时。如果它确实找到了名称为 'test' 的国家/地区,它不会更新状态。

最终,它还会返回 c 中的国家,无论是在找到还是创建之后。

create_with 仅在从关系对象创建新记录时设置属性。

关于ruby-on-rails - first_or_create 只插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51435716/

相关文章:

sql - 对 JSONB 数组字段中的所有项目求和

ruby-on-rails - 首次 bundle 安装,堆栈级别太深

ruby 的 :yields:

javascript - 开发一个清理用户输入的电话号码的功能 - 作业警告

ruby-on-rails - 数组数组 ruby​​ on rails

ruby-on-rails - 使用 Sidekiq 时由对等方重置连接

ruby-on-rails - Ruby url 到 html 链接转换

ruby-on-rails - Rails 模型单一化无法正常工作

python - 编程新手,需要有关 python 中 if - elif 输入的帮助

javascript - 单击时两个字符串的文本不匹配