如何区分first_or_create搜索或创建的内容

时间:2013-01-09 13:09:32

标签: ruby activerecord ruby-on-rails-3.2

我想区分搜索或创建的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

我该怎么做?

2 个答案:

答案 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
  ...