2017-09-19 48 views
0

我有A模型,B模型和Connecting模型。通过第三表加入的关联

A和B有一个con_id列,它是连接模型中的ID。

我试着做到以下几点: 在答:

has_many :connectings 
has_many : bs, :through => connectings 

在B:

has_many :connectings 
has_many :as, :through => connectings 

然后在连接:

belongs_to :as 
belongs_to :bs 

然后试图使连接和包括查询:

A.joins(:bs).includes(:connectings).where("my_condition") 

失败。

我在做什么错?

+0

在你的'Connecting'模型使它奇异。 'belongs_to:a#外键 - a_id' 'belongs_to:b#外键 - b_id'。此外,如果这是您的实际代码,则A模型中的':'和'bs'之间会有一个空格。以下是一些[文档]的参考(http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#module-ActiveRecord:Associations::ClassMethods-label-Many-to-many) – user3366016

回答

0

根据你在问题开始的评论,我猜你的模型和迁移安装不正确。 AB型号和表格不应有con_id列。外键应该在连接表中。

你的模型应该是这样的:

class Connecting < ActiveRecord::Base 
    belongs_to :a # foreign key - a_id 
    belongs_to :b # foreign key - b_id 
end 
class A < ActiveRecord::Base 
    has_many :connectings 
    has_many :bs, through: :connectings 
end 
class B < ActiveRecord::Base 
    has_many :connectings 
    has_many :bs, through: :connectings 
end 

我想删除您的模型和回滚您的迁移和重做。以下是rails guides for has_many :through associations指导您完成设置。

一个基本的迁移,从导轨导向通过,将是这个样子:

# Hope the tables and models have better names, 'as' might cause issues.  
class CreateConnectings < ActiveRecord::Migration[5.0] 
    def change 
    create_table :as do |t| 
     t.string :name 
     t.timestamps 
    end 

    create_table :bs do |t| 
     t.string :name 
     t.timestamps 
    end 

    create_table :connectings do |t| 
     t.belongs_to :a, index: true 
     t.belongs_to :b, index: true 
     t.timestamps 
    end 
    end 
end