2011-07-12 23 views
1

この問題は数回は参照されていますが、あまりにも完全ではありません。私は、単一のモデルのための結合テーブルの使用に問題があります。たとえば、ユーザーとハイファイブがあるとします。 Highfivesは2人のユーザーのハイキングのための結合表に過ぎません。 、私がすべき本当に単一のテーブルからの複数の参照

SELECT "highfives".* FROM "highfives" WHERE "highfives"."user_id" = 1 

:それはのようなクエリを生成するのでこれで、私は(1).highfives User.findような何かを行うことができません、しかし

class Highfive < ActiveRecord::Base 
    belongs_to :user1, 
      :class_name => "User" 

    belongs_to :user2, 
      :class_name => "User" 
end 

class User < ActiveRecord::Base 
    has_many :highfives 
end 

:だから私はこれを持っています

SELECT "highfives".* FROM "highfives" WHERE "highfives"."user1_id" = 1 or "highfives"."user2_id" = 1 

私は想像しています。何らかの方法で自分のユーザーモデルを変更する必要があります。しかし、私は何が欠けていますか?

ありがとうございました。

答えて

1

外部キー。 Userは自分自身をhighfiveすることは不可能だと仮定すると、

class User < ActiveRecord::Base 
    def highfives 
    Highfive.where("user1_id = ? or user2_id = ?", id, id) 
    end 
end 

または::あなたのケースでは、あなたはおそらく代わりにインスタンスメソッドをしたいと思い、私は `foreign_key`があるべきと考えてい

class User < ActiveRecord::Base 
    has_many :highfives1, :class => "Highfive", :foreign_key => :user1_id 
    has_many :highfives2, :class => "Highfive", :foreign_key => :user2_id 
    def highfives 
    highfives1 + highfives2 
    end 
end 
+0

これはとても簡単です。なぜ私はそれを見落としたのか分かりません。ありがとう! –

0

あなたのモデルに:foreign_keyを指定してください。

もちろん
class User < ActiveRecord::Base 
    has_many :highfives, :foreign_key => :user1_id 
end 

、単一のためのこの唯一の作品:あなたがそうでなければRailsはそれがuser_idだと仮定します、あなたのhas_many文で外部キーを指定する必要があります..だから

class Highfive < ActiveRecord::Base 
    belongs_to :user1, 
      :class_name => "User", 
      :foreign_key => "user1_id" 

    belongs_to :user2, 
      :class_name => "User", 
      :foreign_key => "user2_id" 
end 

class User < ActiveRecord::Base 
    has_many :highfive1, 
      :class_name => "Highfive", 
      :foreign_key => "highfive1_id" 
    has_many :highfive2, 
      :class_name => "Highfive", 
      :foreign_key => "highfive2_id" 
end 

Reference!

+0

を' user1_id'/'user2_id'。 –

関連する問題