2016-03-24 7 views
1

私は関係にhas_manyを持っている - にhas_manyのように:私はBaz.first.bar_idsをすればfoo_idsメソッドのthrougth関係でレールが結合するのはなぜですか?

class baz < ActiveRecord::Base 
    has_many :foo 
    has_many :bar, through: :foo 
end 

class foo < ActiveRecord::Base 
    belongs_to :baz 
    belongs_to :bar 
end 

class bar < ActiveRecord::Base 
    has_many :foo 
    has_many :baz, through: :foo 
end 

は、レールが...なぜバーテーブルに参加する代わりに、fooのテーブルにbar_id取得しますか?あなたは独立したエンティティとしてセットアップに関係モデルが必要な場合はhas_many :through関係を設定する必要があり

SELECT [DISTINCT] `foo`.bar_id FROM `foo` WHERE `foo`.`baz_id` = 1 

答えて

1

:対応する例では、結果はこのようなものでなければなりません

class baz < ActiveRecord::Base 
    has_many :foo 
    has_many :bar, through: :foo 
end 

class foo < ActiveRecord::Base 
    belongs_to :baz 
    belongs_to :bar 
end 

class bar < ActiveRecord::Base 
    has_many :foo 
    has_many :baz, through: :foo 
end 

の下になりますあなたはいつも彼のIDを返します。

Railsはあなたが探している要素がテーブルに存在すると考えています。

編集

あなたは私が `にhas_manyを追加Bazクラス

class Baz < ActiveRecord::Base 
    has_many :foo 
    has_many :bar, through: :foo 

    def bar_ids 
     Foo.uniq.pluck(:bar_id).where(baz_id: self.id) 
    end 
end 
+0

を使っています。この動作を変更することは可能ですか?どのようにそれをオーバーライド? – Matrix

+0

@Matrix、私は答えを編集しました –

1

:期待

SELECT `bar`.id FROM `bar` INNER JOIN `foo` ON `bar`.`id` = `foo`.`bar_id` WHERE `foo`.`baz_id` = 1 

:それは役に立たない目地棒

SQLログです。結合モデルで検証、コールバック、または追加の属性が必要な場合は、has_many :throughを使用する必要があります。あなたの期待される結果は、あなたがbarテーブルから行を削除した場合bar_idsは、fooテーブルに存在していた戻ります

# baz = Baz.first 
# bar = Bar.first 

# baz.foo.create(bar: bar) 

# baz.bars #= [bar] 
+0

bar_idsメソッドを追加行うことができます。この動作を変更するには:バズ、trougth:foo'このsloveない問題 – Matrix

+1

それがされます'through::foo'ではなく' trought::foo'です。タイプミスを修正してください。 –

+0

メッセージの間違いでしたが、コードでは^^ – Matrix

関連する問題