Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails ActiveRecord Create or Find

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
like image 1000
ny95 Avatar asked Jul 28 '13 04:07

ny95


1 Answers

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.

like image 60
zeantsoi Avatar answered Oct 08 '22 14:10

zeantsoi