gpt4 book ai didi

ruby - 如何区分由 first_or_create 搜索或创建的

转载 作者:数据小太阳 更新时间:2023-10-29 07:46:42 30 4
gpt4 key购买 nike

我想区分由 first_or_create 搜索或创建。

record = MasterRecord.where(:name=>'test_data').firest_or_create

# and i want differentiate searched or created like this.
# but there is no created_record? method
if record.created_record?
render :status=>200, :json => record.to_json
else
render :status=>409, :json => record.to_json
end

我该怎么做?

最佳答案

解决方法是使用 first_or_initialize 而不是 first_or_create 然后使用 new_record? 如下:

record = MasterRecord.where(:name=>'test_data').first_or_initialize

created_record = record.new_record?
record.save! if record.new_record?

if created_record
render :status=>200, :json => record.to_json
else
render :status=>409, :json => record.to_json
end

关于ruby - 如何区分由 first_or_create 搜索或创建的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14235934/

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