我正在使用Rails 4应用程序,并且在api的post方法中,我想根据用户尝试创建的内容查找记录,如果该记录不存在,请创建该记录,并且是否确实更新了该参数具有。我写了一些实际执行此操作的代码,但是执行起来需要一些时间。还有其他方法可以用更少的代码或查询来完成相同的事情。

@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 release notes表示尚未弃用find_by_ :



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

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

更新:

根据source code:
# 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

09-10 10:22
查看更多