设置多态关联
我试图在我的网站上添加“跟随”function,但我找不到使用多态关联的正确方法。 用户需要能够遵循3个不同的类,这3个类不会跟随用户。 我在过去创建了一个跟随用户的用户,但事实certificate这更加困难。
我的移民是
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 true has_many :followers, :class_name => "User" end
在我的用户模型中
has_many :relationships, :foreign_key => "supporter_id", :dependent => :destroy
以及其他3个型号
has_many :relationships, :as => :relations
我错过了设置这种关联的东西吗?
你基本上是正确的,除了一些小错误:
-
attr_accessible :relations_id
是多余的。 从Relationship
模型中删除它。 -
Relationship
模型和User
模型都调用has_many
来相互关联。Relationship
应该调用belongs_to
因为它包含外键。 -
在您的
User
模型中,设置:foreign_key => "follower_id"
。
我就是这样做的。
在可Follow
的内容方面使用具有多态关联的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
包含在您的三个可跟随的课程中:
has_many :follows, :as => :followable
你现在可以这样做:
TheContent.follows # => [Follow,...] # Useful for counting "N followers" User.follows # => [Follow,...] Follow.follower # => User Follow.followable # => TheContent