2016-07-21 2 views
0

Event이 저장되지만 새 양식에서 여러 아티스트를 선택한 경우에도 "artists":[]이 비어 있습니다. 새로운 형태의 관련 부분은 다음과 같습니다배열 출력을 조인 테이블 (허용되지 않은 매개 변수)로 저장

<%= f.fields_for :event_artists do |fea| %> 
    <%= fea.collection_select :artist_id, Artist.all, "id", "name", {include_blank: true}, {multiple: true} %> 
    <% end %> 

로그 : 여기

Parameters: {"utf8"=>"✓", "authenticity_token"=>"OEh0j/cp35s/FABhsETxeQKnqZCKXrbZMpeeEE6P+KSM3QVF94zIluB1rqAD65ci5CP+R6tQS8V1f3SXIQ6Vtw==", "event"=>{"name"=>"", "date(1i)"=>"2016", "date(2i)"=>"7", "date(3i)"=>"22", "date(4i)"=>"01", "date(5i)"=>"55", "description"=>"", "venue_id"=>"1", "event_artists_attributes"=>{"0"=>{"artist_id"=>["", "1", "2"]}}}, "commit"=>"Create"} 
Unpermitted parameter: artist_id 

이 매개 변수가

def event_params 
    params.require(:event).permit(:id, :name, :date, :venue_id, :description, { event_artists_attributes: [:artist_id] }) 
end 

event_artist 모델은 다음과 같습니다 컨트롤러에 허용됩니다 :

class EventArtist < ApplicationRecord 
    belongs_to :event, optional: true 
    belongs_to :artist 
end 

이벤트 모델 :

class Event < ApplicationRecord 
    belongs_to :venue 
    has_many :event_artists 
    has_many :artists, through: :event_artists 
    accepts_nested_attributes_for :event_artists, reject_if: :all_blank, allow_destroy: true 

end 

이벤트 컨트롤러 :

def create 
    @event = Event.new(event_params) 

    if @event.save 
     render json: @event, status: :created, location: @event 
    else 
     render json: @event.errors, status: :unprocessable_entity 
    end 
    end 

    def new 
    @event = Event.new 
    @artist = @event.event_artists.build 
    end 

답변

1

당신은 불필요한 해시의 내부 event_artists_attributes 있습니다. 대신 다음을 사용하십시오.

params.require(:event).permit(:id, :name, :date, :venue_id, :description, event_artists_attributes: [artist_id]) 

다른 문제가 있습니다. 에 belongs_to 하나의 아티스트 ID를 설정하려고 시도하고 있습니다. 하나만 Artist입니다.

컨트롤러 :

def event_params 
    params.require(:event).permit(:id, :name, :date, 
           :venue_id, :description, artist_ids: []) 
end 

그리고 형태

<%= fields_for… 블록을 제거하고로 교체 :

<%= f.collection_select :artist_ids, Artist.all, "id", "name", 
          {include_blank: true}, {multiple: true} %> 
+0

흠, 아직 허용되지 않은 오류 – sivanes

+0

전체 매개 변수 해시를 덤프 할 수 있습니까? –

+0

게시물을 업데이트했습니다. – sivanes

0

이 시도가 :

params.require(:event).permit(:id, :name, :date, :venue_id, :description, { event_artists_attributes: [artist_id: []] }) 
+0

하지 당신이 당신의 Event 모델에 has_many artists, through: :event_artists을 가지고 있기 때문에, 당신은 다음을 변경할 수 있습니다 일. 콘솔에서 (0.2ms) ROLLBACK [active_model_serializers] ActiveModel :: Serializer :: Null을 ActiveModel :: Errors (0.35ms)와 함께 렌더링 함 (브라우저에서 : {{ "event_artists.artist") 완료 됨 422 Unprocessable Entity' – sivanes

+0

id 배열에 빈 요소가 있기 때문입니다. 콜렉션 select에서'{include_blank : true}'를 제거해야합니다. – Ivan

관련 문제