我正在开发 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
The Rails 4.0 发行说明表示find_by_
has not已弃用:
所有动态方法except对于 find_by_... 和 find_by_...!是
已弃用。
此外,根据Rails 4.0 文档, the find_or_create_by
method is still可用,但已被重写以符合以下语法:
@picture = current_picture.posts.find_or_create_by(post_id: params[:id])
UPDATE:
根据源代码:
# rails/activerecord/lib/active_record/relation.rb
def find_or_create_by(attributes, &block)
find_by(attributes) || create(attributes, &block)
end
因此,多个属性可以作为参数传递给find_or_create_by
在 Rails 4 中。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)