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
You can do it as follows,
@picture = current_picture.posts.where(post_id: params[:id]).find_or_create.
This will find post with params[:id] and if it doesn't find that record then it will create record post under current picture with this id.
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.