2012-01-17 88 views
1

我想向我的網站添加一個「跟隨」類似功能,但我無法找到使用多態關聯的正確方法。用戶需要能夠遵循3個不同的類別,這3個類別不會跟隨用戶回來。我在過去創建了一個用戶,但這被證明比較困難。設置多態關聯

我的移民是

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 

我的關係模式是

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

在我的用戶模型

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

和其他3款

has_many :relationships, :as => :relations 

我是否錯過了設置此關聯的內容?

+0

你試過通過控制檯測試呢?確保你也運行你的遷移。什麼是'其他3個模型'? – 2012-01-17 07:18:37

+0

你能否詳細說一下'has_many:relationship,:foreign_key =>「supporter_id」'? – 2012-01-17 07:21:42

+0

對不起,「supporter_id」是一個錯字 – 2012-01-17 16:09:59

回答

5

你基本上是正確的,除了一些小錯誤:

  • attr_accessible :relations_id是多餘的。將它從您的Relationship模型中移除。

  • RelationshipUser模型都呼籲has_many彼此關聯。 Relationship應該調用belongs_to,因爲它包含外鍵。

  • 在您的User型號中,設置爲:foreign_key => "follower_id"


這裏是我會怎麼做。

followable內容端有Follow中間類,在follower用戶端具有多態關聯,用戶有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 

更換Relationship模型與Follow模型:

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

包括在User模型:

has_many :follows, :foreign_key => :follower_id 

包含在你的三個隨動班級:

has_many :follows, :as => :followable 

現在你可以這樣做:

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

非常感謝您的幫助,我現在遇到了執行跟隨和取消關注表單的問題,只要創建操作。有小費嗎 ? – 2012-01-19 06:03:38