3

我想区分由 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

我该怎么做呢?

4

2 回答 2

5

一种解决方法是使用first_or_initializefirst_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
于 2013-01-09T13:42:52.820 回答
3

如果找不到记录会返回[],所以你可以玩tap。像这样的东西:

created = false
record = MasterRecord.where(:name=>'test_data').tap {|x| created = true if x.empty?}.first_or_create
if created
  ...
于 2013-01-09T13:38:36.027 回答