0

안녕하세요 중첩 된 특성을 사용하여 기능을 구현하려고합니다. (고객을 위해) 핸디캡을 생성하기위한 폼에서 모든 고객의 리그 목록을 표시하고 싶습니다. 그리고 폼이 Create 액션으로 제출 될 때 @ handicap.save를 사용하면 핸디캡 및 리그 (형태로 선택된 리그)도 포함됩니다.많은 수의 레일 중첩 된 특성

유일한 해결책은 중첩 된 특성을 사용하지 않고 발견했습니다. 새 방법에서는 고객의 모든 장애를 받고 양식에 표시합니다. 따라서 양식을 생성 작업에서 제출하면 유효성 검사를 할 것입니다. 고객의 @handicap 레코드를 만들고 수동으로 연관을 만들려는 양식의 각 리그 ID를 수동으로 만듭니다.

#New/Create actions in the handicaps controller 

def new 
    @leagues = @customer.leagues 
end 

def create 
    handicap = @customer.handicaps.build(handicap_params) 
    if handicap.save 
    associations = [] 
    params[:league_ids].each do |id| 
     associations << LeagueHandicap.new(handicap_id: @handicap.id, league_id: id) 
    end 
    LeagueHandicap.import(associations) 
    end 
end 

나는 handicap.save를하고 자동으로 리그 핸디캡 협회를 만들고 싶습니다. 그러나 중첩 된 특성을 사용하여이를 수행하는 방법에 대한 단서가 없습니다. 이렇게 할 수 있습니까?

답변

0

(LeagueHandicap을 통해 장애인과 리그 사이 많은 관계로 많은)

class Customer < ActiveRecord::Base 
    has_many :handicaps, dependent: :destroy 
    has_many :leagues, dependent: :destroy 
end 

class Handicap < ActiveRecord::Base 
    belongs_to :customer 
    has_many :league_handicaps 
    has_many :leagues, through: :league_handicaps, dependent: :destroy 
end 

class LeagueHandicap < ActiveRecord::Base 
    belongs_to :handicap 
    belongs_to :league 
end 

class League < ActiveRecord::Base 
    has_many :league_handicaps 
    has_many :handicaps, through: :league_handicaps, dependent: :destroy 
end 

당신이 league_ids 레일이 당신을 위해 그 (것)들을 추가해야합니다 허용하는 경우 :

나는 다음과 같은 모델을 가지고있다. 레일즈에 어레이라고 말할 필요가있다.

def handicap_params 
    params.require(:handicap).permit(league_ids: []) 
end 
+0

그리고 폼에 고객 @ 리그를 어떻게 표시 할 수 있습니까? 양식이 제출자 인 경우 {handicap : {info_about handicap : {}, league_ids : [1, 2, 3]}}와 같은 금액이됩니다. 나는보기에서 리그를 cocorrectly 표시하는 것이 어렵다. 나는 sumthing을 다음과 같이 사용할 필요가있다 : f.fields for : leagues do | builder | ? –

+0

['collection_check_boxes'] (http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-collection_check_boxes)'f.collection_check_boxes (league_ids, League.all, : id, :)와 같은 것입니다. 이름)' –

+0

잘 작동합니다! 그러나 우리는 편집 방법에 대해 동일한 방법을 사용할 수 없습니다. collection_check_boxes를 사용하면 update 메소드의 검사를 변경하더라도 레일스는 마지막 연관성을 삭제하지 않고 새로운 연관성을 생성합니다. 레일에 그렇게하도록 지시하는 방법이 있습니까? 그렇다면 하드 코딩 할 필요가 없습니까? –