Rails ActiveRecord创建或查找

我正在开发一个Rails 4应用程序,并在我的post方法中为api我想根据用户尝试创建的内容找到记录,如果它不存在则创建它,如果它确实更新了它的参数具有。 我编写了一些实际执行此操作的代码,但需要执行一些操作。 有没有其他方法可以用可能更少的代码或查询做同样的事情。

@picture = current_picture.posts.where(post_id: params[:id]).first_or_initialize @picture.update_attributes(active: true, badge: parameters[:badge], identifier: parameters[:identifier]) render json: @picture 

Rails 4.0发行说明表示尚未弃用find_by_

除了 find_by _…和find_by _… 之外的所有动态方法! 不推荐使用。

此外,根据Rails 4.0文档 , find_or_create_by方法仍然可用,但已被重写以符合以下语法:

 @picture = current_picture.posts.find_or_create_by(post_id: params[:id]) 

更新:

根据源代码 :

 # rails/activerecord/lib/active_record/relation.rb def find_or_create_by(attributes, &block) find_by(attributes) || create(attributes, &block) end 

因此,可以将多个属性作为参数传递给Rails 4中的find_or_create_by

你可以这样做,

@picture = current_picture.posts.where(post_id:params [:id])。find_or_create。

这将找到带有params [:id]的post,如果找不到该记录,那么它将使用此id在当前图片下创建记录post。