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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With