我想区分搜索或创建的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
我该怎么做?
答案 0 :(得分:5)
解决方法是使用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
答案 1 :(得分:3)
如果找不到记录,则返回[]
,因此您可以使用tap
。
像这样:
created = false
record = MasterRecord.where(:name=>'test_data').tap {|x| created = true if x.empty?}.first_or_create
if created
...