2012-04-02 83 views
0

你好,我正在嘗試構建一個多選擇來填充多對多連接表。我可以創建新的新表單,但當我試圖保存我的記錄時,會收到「AssociationTypeMismatch」。 我在網上找到的解決方案並不能解決我的問題。
希望有人能解決什麼,我應該怎樣做才能擺脫 「AssociationTypeMismatch」ActiveRecord :: AssociationTypeMismatch在多對多關係中

class Presenter < ActiveRecord::Base 
    belongs_to :seminar 
    belongs_to :person 
end 

class Seminar < ActiveRecord::Base 
    attr_accessible :description, :title, 
    has_many :presenters, :foreign_key => "person_id" 
    has_many :lecturer, :through => :presenters, :source => :person 
    accepts_nested_attributes_for :lecturer, :presenters 
end 

class Person < ActiveRecord::Base 
    attr_accessible :first_name, :last_name 
    has_many :presentors 
    has_many :lecturingAt, :through => :presentors 

    def fullName 
     first_name + " " + last_name 
    end 
end 

seminars_controller.rb

def new 
    @seminar = Seminar.new 
    @current_presenters = Person.find(:all) 
    respond_to do |format| 
    format.html # new.html.erb 
    format.xml { render :xml => @seminar } 
    end 
end 
.... 
def create 
    @seminar = Seminar.new(params[:seminar]) 
    respond_to do |format| 
    if @seminar.save 
     format.html { redirect_to(@seminar, :notice => 'Seminar was successfully created.') } 
     format.xml { render :xml => @seminar, :status => :created, :location => @seminar } 
    else 
     format.html { render :action => "new" } 
     format.xml { render :xml => @seminar.errors, :status => :unprocessable_entity } 
    end 
    end 
end 

研討會/ _form.html.erb的。有填充我的收藏選擇與 可能的lecurers的名稱和persions ID。

.... 
<div class="field"> 
<%= f.label :presenter_id %><br /> 
<%= collection_select(:seminar,:lecturer,@current_presenters, :id, :fullName,{}, {:multiple=>true}) %> 
.... 

在提交傳遞到我控制器PARAMS

Parameters: {...., "seminar"=>{ "lecturer"=>["1", "2"], "title"=>"1234567890", "description"=>"ASDFGHJKL:"}, "commit"=>"Create Seminar"} 

四處錯誤:

ActiveRecord::AssociationTypeMismatch (Instructor(#86075540) expected, got String(#73495120)):.

+0

難道你用formtastic來試試這個。它有很多選項可以顯示與複選框的多對多關係。 https://github.com/justinfrench/formtastic – Sairam 2012-04-02 00:10:55

回答

1
@seminar = Seminar.new 

試試這個

@seminar.lecturer_ids = params[:seminar].delete(:lecturer) 
@seminar.update_attributes(params[:seminar]) 
+0

非常感謝你。 UMMM。但如果我刪除講師參數。如何設置連接表信息? – 2012-04-02 01:26:37

+0

哦,我想我知道它是如何完成的 – 2012-04-02 01:28:55

+0

確定它正在填充連接表的1/2。 seminar_id被設置爲null。我如何設置研討會ID? @ seminar.lecturer.seminar_id? – 2012-04-02 02:11:21