Rails ActiveRecord Create or Find

后端 未结 2 1717
甜味超标
甜味超标 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:40

    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.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题