2012-01-17 8 views
1

"次のような"機能を私のサイトに追加しようとしていますが、多型関連を使用する正しい方法を見つけるのが難しいです。ユーザーは3つの異なるクラスに従うことができる必要があります。これらの3つのクラスはユーザーの背後にはありません。私は過去にユーザーの後にユーザーを作成しましたが、これはより困難であることが証明されています。多型関連を設定する

私の移行は、私の関係のモデルは

has_many :relationships, :foreign_key => "supporter_id", :dependent => :destroy 

およびその他の3つのモデルで、私のUserモデルで

class Relationship < ActiveRecord::Base 
    attr_accessible :relations_id 
    belongs_to :relations, :polymorphic => true 
    has_many :followers, :class_name => "User" 
end 

ある

class CreateRelationships < ActiveRecord::Migration 
    def change 
    create_table :relationships do |t| 
     t.integer :follower_id 
     t.integer :relations_id 
     t.string :relations_type  
     t.timestamps 
    end 
    end 
end 

has_many :relationships, :as => :relations 

この関連付けの設定に何か不足していますか?

+0

は、コンソール経由でこれをテストしてみましたがありますか?移行も必ず実行してください。 「他の3つのモデル」とは何ですか? –

+0

'has_many:relationships、:foreign_key =>" supporter_id "'について詳しく説明できますか? –

+0

申し訳ありませんが、 "supporter_id"はタイプミスでした –

答えて

5

あなたは基本的にいくつかのマイナーなエラーを除いて、右のそれを持っている:

  • attr_accessible :relations_idは冗長です。 Relationshipモデルから削除します。

  • RelationshipおよびUserモデルは、互いに関連付けるためにhas_manyを呼び出します。 Relationshipには、外部キーが含まれているので、belongs_toを呼び出す必要があります。

  • Userモデルでは、:foreign_key => "follower_id"と設定します。ここで


私はそれを行うだろうかです。

followableのコンテンツ側にFollowの多面的な関連付けを持ち、followerユーザー側にhas_manyを持っています(ユーザーは以下が多い)。

まず、followsテーブルを作成します。

class CreateFollows < ActiveRecord::Migration 
    def change 
    create_table :follows do |t| 
     t.integer :follower_id 
     t.references :followable, :polymorphic => true 
     t.timestamps 
    end 
    end 
end 

FollowモデルとRelationshipモデルを置き換えます

class Follow < ActiveRecord::Base 
    belongs_to :followable, :polymorphic => true 
    belongs_to :followers, :class_name => "User" 
end 

Userモデルに含める:

has_many :follows, :foreign_key => :follower_id 

は、あなたの3つの追従可能に含めますクラス:

has_many :follows, :as => :followable 

あなたは今、この操作を行うことができます。

TheContent.follows # => [Follow,...] # Useful for counting "N followers" 
User.follows   # => [Follow,...] 
Follow.follower  # => User 
Follow.followable # => TheContent 
+0

大変ありがとうございました。私は現在、作成アクションの間、フォローアンドアンフォローフォームの実装に問題があります。任意のヒント ? –

関連する問題