복붙노트

[RUBY-ON-RAILS] 더 하나 개의 속성보다 find_or_create_by 레일?

RUBY-ON-RAILS

더 하나 개의 속성보다 find_or_create_by 레일?

find_or_create_by라는 액티브 레코드에 편리한 동적 속성이 있습니다 :

Model.find_or_create_by_ <특성> (<특성> => "")

하지만 제가 하나 개 이상의 속성에 의해 find_or_create해야하는 경우?

그룹 및 회원 간의 M 관계가 GroupMember라고 : 나는 M을 처리하는 모델을 말한다. 내가 = 4,하지만 내가 더 예를 한 번 이상하지 않으 MEMBER_ID 여러 인스턴스를 가질 수있는 곳 MEMBER_ID = 4 GROUP_ID = 7. 나는 그것이 같은 것을 할 수 있는지 알아 내기 위해 노력하고있어 :

GroupMember.find_or_create(:member_id => 4, :group_id => 7)

나는 find_or_create의 아이디어의 편의처럼이 처리하는 더 나은 방법이있을 수있다 알지만.

해결법

  1. ==============================

    1.여러 속성은과 함께 연결할 수 있습니다 :

    여러 속성은과 함께 연결할 수 있습니다 :

    GroupMember.find_or_create_by_member_id_and_group_id(4, 7)
    

    (당신이 바로 기록을 저장하지 않으려면 사용 find_or_initialize_by)

    편집 : 위의 방법은 레일에서 더 이상 사용되지 않습니다 4.이 될 것입니다 수행하는 새로운 방법 :

    GroupMember.where(:member_id => 4, :group_id => 7).first_or_create
    

    GroupMember.where(:member_id => 4, :group_id => 7).first_or_initialize
    

    편집 2 : 모든이의 레일 단지 속성 특정 것들 밖으로 고려했다.

    https://github.com/rails/rails/blob/4-2-stable/guides/source/active_record_querying.md

    GroupMember.find_or_create_by_member_id_and_group_id(4, 7)
    

    되었다

    GroupMember.find_or_create_by(member_id: 4, group_id: 7)
    
  2. ==============================

    2.이 스레드를 통해 실수를 한단다하지만 찾거나 상황에 따라 변경 될 수 있습니다 속성을 가진 객체를 생성 할 필요가 다른 사람, 모델에 다음과 같은 방법을 추가 할 경우 :

    이 스레드를 통해 실수를 한단다하지만 찾거나 상황에 따라 변경 될 수 있습니다 속성을 가진 객체를 생성 할 필요가 다른 사람, 모델에 다음과 같은 방법을 추가 할 경우 :

    # Return the first object which matches the attributes hash
    # - or -
    # Create new object with the given attributes
    #
    def self.find_or_create(attributes)
      Model.where(attributes).first || Model.create(attributes)
    end
    

    최적화 팁 : 당신이 가장 자주 쿼리하는 속성에 대해 당신이 선택에 관계없이 용액은 인덱스를 추가하는 것이 좋습니다.

  3. ==============================

    3.레일 4에서 당신이 할 수 있습니다 :

    레일 4에서 당신이 할 수 있습니다 :

    GroupMember.find_or_create_by(member_id: 4, group_id: 7)
    

    그리고 사용은 어디 다르다 :

    GroupMember.where(member_id: 4, group_id: 7).first_or_create
    

    이 GroupMember.where에 생성 호출 (MEMBER_ID : 4, GROUP_ID : 7) :

    GroupMember.where(member_id: 4, group_id: 7).create
    

    반대로, find_or_create_by (MEMBER_ID : 4, GROUP_ID : 7) GroupMember에 생성 호출합니다 :

    GroupMember.create(member_id: 4, group_id: 7)
    

    이 관련이 레일에 커밋 참조하십시오 / 레일.

  4. ==============================

    4.find_or_create에 블록을 통과하면이 새로운 생성 된 경우 개체에 추가됩니다 추가 매개 변수를 전달할 수 있습니다. 당신은 당신이에 의해 검색되지 않습니다 필드의 존재를 확인하는 경우에 유용합니다.

    find_or_create에 블록을 통과하면이 새로운 생성 된 경우 개체에 추가됩니다 추가 매개 변수를 전달할 수 있습니다. 당신은 당신이에 의해 검색되지 않습니다 필드의 존재를 확인하는 경우에 유용합니다.

    가정 :

    class GroupMember < ActiveRecord::Base
        validates_presence_of :name
    end
    

    그때

    GroupMember.where(:member_id => 4, :group_id => 7).first_or_create { |gm| gm.name = "John Doe" }
    

    이 MEMBER_ID 4 GROUP_ID 7 일을 찾을 수없는 경우 이름이 "홍길동"으로 새로운 GroupMember을 만듭니다

  5. ==============================

    5.넌 할 수있어:

    넌 할 수있어:

    User.find_or_create_by(first_name: 'Penélope', last_name: 'Lopez')
    User.where(first_name: 'Penélope', last_name: 'Lopez').first_or_create
    

    아니면 그냥 초기화 :

    User.find_or_initialize_by(first_name: 'Penélope', last_name: 'Lopez')
    User.where(first_name: 'Penélope', last_name: 'Lopez').first_or_initialize
    
  6. from https://stackoverflow.com/questions/3046607/rails-find-or-create-by-more-than-one-attribute by cc-by-sa and MIT license