2013-02-08 77 views
0

我試圖在Rails 3.2.11中的兩個模型之間創建多對多的關係。Rails中的多對多關係

用戶可以與許多事件相關聯,反之亦然。

class User < ActiveRecord::Base 
    include ActiveModel::ForbiddenAttributesProtection 

    has_many :incident_participants, foreign_key: "participant_id" 
    has_many :participated_incidents, through: :incident_participants 

end 


class Incident < ActiveRecord::Base 
    include ActiveModel::ForbiddenAttributesProtection 

    has_many :incident_participants, foreign_key: "participated_incident_id" 
    has_many :participants, through: :incident_participants 

end 

連接表:

class IncidentParticipant < ActiveRecord::Base 
    include ActiveModel::ForbiddenAttributesProtection 

    t.belongs_to :participant, class_name: "User" 
    t.belongs_to :participated_incident, class_name: "Incident" 
end 

表IncidentParticipants

create_table "incident_participants", :force => true do |t| 
    t.integer "participant_id" 
    t.integer "participated_incident_id" 
    t.datetime "created_at",    :null => false 
    t.datetime "updated_at",    :null => false 
    end 

那麼,爲什麼不軌得到這個關係?當我嘗試在我的視圖中執行@ incident.participants時,出現此錯誤:

"Could not find the source association(s) :participant or :participants in model IncidentParticipant. Try 'has_many :participants, :through => :incident_participants, :source => '. Is it one of ?"

任何想法?

回答

1

嘗試取出t.belongs_to並替換爲belongs_to

+0

哦,我的上帝......我認爲是時候離開今天的工作:)謝謝! – Linus 2013-02-08 15:07:06

+0

哈哈沒問題。我認爲作爲一種方法存在,因爲你沒有得到一個nil類的nomethoderror,否則你可能會抓住它。 :) – agmcleod 2013-02-08 15:07:57

0

要創建多對多關聯,您應該考慮創建關聯表。也就是說,你將有兩個1-M關係指向一個臨時表。例如:

在你的第一個模型:

class Example < ActiveRecord::Base 
    has_and_belongs_to_many :example2 
end 

在你的第二個模式:

class Example2 < ActiveRecord::Base 
    has_and_belongs_to_many :example 
end 

然後,你需要編寫一個遷移到兩個表連接在一起:

class CreateTableExamplesExamples2 < ActiveRecord::Migration 
    create_table :examples_examples2 do |t| 
    t.integer :example_id 
    t.integer :example2_id 
    end 
end 

然後讓鋼軌魔法工作。查看guides瞭解更多信息。