2016-12-07 123 views
0

我是相當新的軌道和使用多選時,我有一些問題更新我的關聯表。Rails嵌套關聯和多個collection_select

我有三個表,portraitportrait_tagstags

(該標籤存儲我的標籤名稱(傳統,鼓舞人心,社區等)的名稱)

我想要的結果是,「多選場'會根據Tag.all tag_id值將標籤添加到portrait_tag表中。目前,這似乎只插入一個字段,並且portrait_tag表中的tag_id爲NULL,然後當我返回到編輯頁面時,多重選擇被複制。

PARAMS

Parameters: {"utf8"=>"✓", "authenticity_token"=>"j+Obhq9u+mvOKYnj4+TAGy+be8s3AbZlMvuyKiot5iyKqjMyFAcs23PjbQjOTjwl6aRBx1M5lmYRZzTjOeDTJA==", "portrait"=>{"portrait_tags_attributes"=>{"0"=>{"tag_id"=>["", "1", "2"]}}}, "commit"=>"Save changes", "id"=>"72"} 

Tag.rb

class Tag < ActiveRecord::Base 

    has_many :portraits, through: :portrait_tags 
    accepts_nested_attributes_for :portraits 

end 

Portrait.rb

class Portrait < ActiveRecord::Base 

    has_many :portrait_tags 
    has_many :tags, through: :portrait_tags 

    accepts_nested_attributes_for :portrait_tags 

end 

Portrait_tag.rb

class PortraitTag < ActiveRecord::Base 

    belongs_to :portrait 
    belongs_to :tag 

end 

Edit.html.haml

%h1 Edit Portrait 
= form_for [:admin, @portraits], :html => { :method => :put } do |f| 

    - if flash[:system].present? 
    - flash[:system].each do |e| 
     %div= e 

    - if flash[:notice].present? 
    %div= flash[:notice] 

    = f.fields_for :portrait_tags do |a| 
    = a.collection_select :tag_id, Tag.all, :id, :name, {}, {multiple: true} 

    = f.submit "Save changes", class: "btn btn-primary" 

PortraitController

class Admin::PortraitsController < ApplicationController 

    def edit 
     @portraits = Portrait.where(artist_id: 33, id: params[:id]).take 
     @portraits.portrait_tags.build 

    end 

    def update 

     @portrait = Portrait.where(artist_id: 33, id: params[:id]).take 


     if @portrait.update(portrait_params) 

     p portrait_params 

     else 
     flash[:system] = @portrait.errors.full_messages 
     p @portrait.errors.full_messages 

     render :edit 
     end 

    end 

    private 
     def portrait_params 
     # Permit our attributes 
     params.require(:portrait).permit(:id, portrait_tags_attributes: [:id, :tag_id => [] ]) 

     end 



end 

portrait_tags表

+----+-------------+--------+ 
| id | portrait_id | tag_id | 
+----+-------------+--------+ 

畫像表

+----+-----------+--------------+ 
| id | artist_id | artist_image | 
+----+-----------+--------------+ 

標籤表

+----+-----------+--------------------+ 
| id | name | portrait_tag_id | 
+----+-----------+--------------------+ 

回答

2
<%= collection_select(:portrait_tag, :tag_ids, 
       Tag.all(:order=>"name ASC"), 
       :id, :name, {:selected => @portraits.tag_ids, :include_blank => true}, {:multiple => true}) %> 

希望這會爲你工作。

+0

謝謝,這工作。你能解釋一下爲什麼?我正在努力解決這個問題! – Adam

+0

在這種情況下,使用fields_for是錯誤。 –

+0

Thanks Atul, 如果我在form_for中有另外一個字段,我該如何將param傳遞給多個? params.require(:portrait).permit(:id,:artist_image) params.require(:portrait_tag).permit(:id,:tag_ids => []) – Adam