Rails ActiveRecord 创建或查找 [英] Rails ActiveRecord Create or Find
问题描述
我正在开发一个 Rails 4 应用程序,在我的 api 发布方法中,我想根据用户尝试创建的内容查找记录,如果它不存在,则创建它,如果它确实更新了它具有的参数.我编写了一些实际执行此操作的代码,但执行起来需要一些时间.有没有其他方法可以用更少的代码或查询来做同样的事情.
I'm working on a Rails 4 App and in my post method for an api i want to find the record based on what the user is trying to create and if it doesn't exist create it and if it does update the parameters that it has. I wrote some code that actually does this but it takes a bit to execute. Is there any other way of doing the same exact thing with possibly less code or queries.
@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
推荐答案
Rails4.0 发行说明表示find_by_
尚未被弃用:
所有动态方法除了 find_by_... 和 find_by_...!是已弃用.
All dynamic methods except for find_by_... and find_by_...! are deprecated.
此外,根据 Rails 4.0 文档,find_or_create_by
方法仍然可用,但已被重写以符合以下语法:
Additionally, according to the Rails 4.0 documentation, the find_or_create_by
method is still available, but has been rewritten to conform to the following syntax:
@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
是理所当然的.
Thus, it stands to reason that multiple attributes can be passed as arguments to find_or_create_by
in Rails 4.
这篇关于Rails ActiveRecord 创建或查找的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!