Rails的ActiveRecord的创建或找到 [英] Rails ActiveRecord Create or Find

查看:111
本文介绍了Rails的ActiveRecord的创建或找到的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个Rails 4应用程序,并在我的岗位方法的API的工作我想找到根据用户正在尝试创建记录,如果它不存在,创建它,如果它不更新它具有的参数。我写了一些code,实际上做到这一点,但它需要多一点来执行。是否有这样做同样的事情有可能少于code或查询的任何其他方式。

  @picture = current_picture.posts.where。(的post_id:PARAMS [:ID])first_or_initialize
@ picture.update_attributes(活动:真,徽章:参数[:徽章],标识符:参数[:标识符])
渲染JSON:@picture
 

解决方案

href="http://edgeguides.rubyonrails.org/4_0_release_notes.html#active-record-de$p$pcations">的Rails 4.0 表示了 find_by _ 也没有被撤销precated:

  

所有的动态方法的除了的为find_by _...和find_by _...!是   德precated。

此外,根据本<一href="http://api.rubyonrails.org/classes/ActiveRecord/Relation.html#method-i-find_or_create_by">Rails 4.0文档,在 find_or_create_by 方法的还是可用,但已被改写,以符合语法如下:

  @picture = current_picture.posts.find_or_create_by(的post_id:PARAMS [:ID])
 

更新:

根据<一href="https://github.com/rails/rails/blob/24c4195bab27ed9d76d0e126044e7f932de9e30e/activerecord/lib/active_record/relation.rb">source code :

 #导轨/ ActiveRecord的/ lib目录/ active_record / relation.rb
高清find_or_create_by(属性,和放大器;块)
  find_by(属性)||创建(属性,和放大器;块)
结束
 

因此​​,按理说在Rails的多个属性可以作为参数传递给 find_or_create_by 4。

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

解决方案

The Rails 4.0 release notes denote that find_by_ has not been deprecated:

All dynamic methods except for find_by_... and find_by_...! are deprecated.

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])

UPDATE:

According to the source code:

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

Thus, it stands to reason that multiple attributes can be passed as arguments to find_or_create_by in Rails 4.

这篇关于Rails的ActiveRecord的创建或找到的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆