2017-09-19 11 views
0

Aモデル、Bモデル、Connectingモデルです。第3テーブルによる結合のための関連

AとBは接続モデルのIDであるcon_idの列を持ちます。接続に続いて

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

: で:

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

Bで

は、私は次の操作を実行しようとした
belongs_to :as 
belongs_to :bs 

が続いて参加するようにしようとクエリを含む:

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

失敗します。

私は間違っていますか?

+0

は、それが特異作る:レールガイドから採用

基本的な移行は、次のようになります。 'belongs_to:a#foreign key - a_id' ' belongs_to:b#foreign key - b_id'です。また、これが実際のコードであれば、Aモデルの ':'と 'bs'の間にスペースがあります。ここにいくつかの[docs](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はここにあります。あなた `Connecting`モデルで

# 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 
関連する問題