Rails ActiveRecord Create or Find

后端 未结 2 1716
甜味超标
甜味超标 2021-01-11 18:24

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

2条回答
  •  情话喂你
    2021-01-11 18:45

    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.

提交回复
热议问题