设置多态关联 [英] Setting up a polymorphic association

查看:43
本文介绍了设置多态关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试向我的网站添加类似跟随"的功能,但我无法找到使用多态关联的正确方法.用户需要能够关注 3 个不同的类,这 3 个类不会跟随用户.我过去创建了一个用户关注用户,但事实证明这更加困难.

I am trying to add a "following" like functionality to my site but I am having trouble finding the right way to use a polymorphic association. A user needs to be able to follow 3 different classes, these 3 classes do not follow the user back. I have created a user following user in the past but this is proving to be more difficult.

我的迁移是

 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

我是否在设置此关联时遗漏了什么?

推荐答案

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

You basically have it right, except for a few minor errors:

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

  • attr_accessible :relations_id is redundant. Remove it from your Relationship model.

RelationshipUser 模型都调用 has_many 来相互关联.Relationship 应该调用 belongs_to 因为它包含外键.

Both Relationship and User models call has_many to associate with each other. Relationship should call belongs_to because it contains the foreign key.

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

In your User model, set :foreign_key => "follower_id".

这就是我的做法.

followable 内容端有一个具有多态关联的Follow 中间类,在follower 用户端有一个has_many(用户有很多关注).

Have a Follow middle class with polymorphic association on the followable content side and has_many on the follower user side (user has many follows).

首先,创建一个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 模型:

Replace Relationship model with a Follow model:

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

包含在 User 模型中:

has_many :follows, :foreign_key => :follower_id

包括在您的三个可关注类中:

Include in your three followable classes:

has_many :follows, :as => :followable

您现在可以这样做:

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

这篇关于设置多态关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆