首页 文章

Rails中的多对多关系

提问于
浏览
0

我试图在Rails 3.2.11中创建两个模型之间的多对多关系 .

用户可以与许多事件相关联,反之亦然 .

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时,我收到此错误:

“找不到源关联:参与者或模型IncidentParticipant中的参与者 . 尝试'has_many:参与者,:through =>:incident_participants,:source =>' . 是否是其中之一?”

有任何想法吗?

2 回答

  • 0

    尝试取出 t.belongs_to 并替换为 belongs_to .

  • 1

    要创建多对多关联,您应该考虑创建关联表 . 也就是说,您将有两个指向临时表的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 .

相关问题