2013-03-20 2 views
3

나는 중첩 된 폼에 대해 이해하는 데 어려움을 겪고 있습니다. 사용자는 애플리케이션에 로그인하고 '팀 생성'을 클릭하면이 페이지에서 팀 이름과 팀 구성원 목록을 입력 할 수 있습니다. (효과적으로 팀원 목록을 작성).레일 중첩 된 폼 속성 Building

  • 회원을 만들려면 멤버십이 fields_for 인 중첩 된 양식이 있습니다. See screenshot of form
  • 양식을 저장하면 멤버십 모델에서 Entrant.find_or_creates_by_name을 실행하여 참가자를 만듭니다.
    • 멤버십 팀이

가 어떻게 발생하지 않도록 허용 할 비워 둘 수 없습니다 : 나는 데

  • 문제는 창조에 나는 오류 메시지를 얻을 수 있다는 것입니다 사용자가 참가자를 추가하거나 멤버십이 올바르게 작성되었는지 확인하십시오. 이 이미 응답 한 경우

    사과 (중첩 된 자원을 통해 has_many에 많은 화제가 될 것 같다,하지만 난 내 특정 문제 처리 찾을 수 없음 (나는

    ) 명확 할 것 같았다/수 다음과 같은 조치를 만들 내

    현재 표준 중첩 된 형태의 작업입니다 :

    나는 다음과 같은 모델을 가지고 :

    사용자 모델

    class User < ActiveRecord::Base 
        has_many :teams 
    end 
    

    팀 모델

    class Team < ActiveRecord::Base 
        belongs_to :user 
        has_many :memberships 
        has_many :entrants, :through => :memberships 
    
        attr_accessible :name, :team_type, :website, :memberships_attributes 
        accepts_nested_attributes_for :memberships, allow_destroy: true 
    end 
    

    멤버십 모델

    class Membership < ActiveRecord::Base 
        belongs_to :team 
        belongs_to :entrant 
    
        validates :team_id, presence: true 
        validates :entrant_id, presence: true 
    
        attr_accessor :entrant_name 
        attr_accessible :entrant_name 
    
        def entrant_name 
        entrant && entrant.name 
        end 
    
        def entrant_name=(name) 
        self.entrant = Entrant.find_or_create_by_name(name) unless name.blank? 
        end 
    
    end 
    

    가입자 모델 - 사용자가 입력하지만 때 효과적으로 memberlistings에 대한 팀의 일원이다 팀마다 닉네임을 지정할 수 있으며 팀마다 변경 될 수 있습니다.

    class Entrant < ActiveRecord::Base 
        attr_accessible :name 
        has_many :memberships 
        has_many :teams, :through => :memberships 
    end 
    
  • +0

    질문에 도움이되는 추가 정보/파일 : [Form View Code] (https://gist.github.com/digitaldawn/fc2edc87dbbe5889ffb9) | [개발 로그] (https://gist.github.com/digitaldawn/c98dd9789094098258eb) –

    답변

    0

    나는 그 검증 오류라고 생각합니다.
    의 유효성을 검사합니다. entrant_id, presence : true
    멤버십 모델에서.

    +0

    물론, 멤버쉽은 참가자와 팀 간의 조인 모델이기 때문에 존재하지 않습니다. –

    +2

    accepts_nested_attributes_for를 사용하면 부모 ID와 자식 ID가 레코드를 저장할 때 해당 부모 및 자식 모델에 대해 자동으로 생성됩니다. – nilay