gpt4 book ai didi

ruby-on-rails - first_or_create 只插入

转载 作者:数据小太阳 更新时间:2023-10-29 08:29:49 26 4
gpt4 key购买 nike

我在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com