设置多态关联

Kyl*_*e C 1 ruby ruby-on-rails ruby-on-rails-3

我正在尝试向我的网站添加"跟随"功能,但我找不到使用多态关联的正确方法.用户需要能够遵循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
Run Code Online (Sandbox Code Playgroud)

我的关系模型是

class Relationship < ActiveRecord::Base
  attr_accessible :relations_id
  belongs_to :relations, :polymorphic => true
  has_many :followers, :class_name => "User"
end
Run Code Online (Sandbox Code Playgroud)

在我的用户模型中

has_many :relationships, :foreign_key => "supporter_id", :dependent => :destroy
Run Code Online (Sandbox Code Playgroud)

以及其他3个型号

has_many :relationships, :as => :relations
Run Code Online (Sandbox Code Playgroud)

我错过了设置这种关联的东西吗?

Sub*_*ial 5

你基本上是正确的,除了一些小错误:

  • attr_accessible :relations_id是多余的.从Relationship模型中删除它.

  • 两者RelationshipUser模型都要求has_many相互关联.Relationship应该调用belongs_to因为它包含外键.

  • 在您的User模型中,设置:foreign_key => "follower_id".


我就是这样做的.

Followfollowable内容方面有一个具有多态关联的中间类,在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
Run Code Online (Sandbox Code Playgroud)

Relationship型号替换Follow型号:

class Follow < ActiveRecord::Base
  belongs_to :followable, :polymorphic => true
  belongs_to :followers, :class_name => "User"
end
Run Code Online (Sandbox Code Playgroud)

包含在User模型中:

has_many :follows, :foreign_key => :follower_id
Run Code Online (Sandbox Code Playgroud)

包含在您的三个可跟随的课程中:

has_many :follows, :as => :followable
Run Code Online (Sandbox Code Playgroud)

你现在可以这样做:

TheContent.follows   # => [Follow,...]  # Useful for counting "N followers"
User.follows         # => [Follow,...]
Follow.follower      # => User
Follow.followable    # => TheContent
Run Code Online (Sandbox Code Playgroud)