【问题标题】:Rails 4: setting up many to many (follower and followed)Rails 4:设置多对多(关注者和关注者)
【发布时间】:2015-07-30 06:37:55
【问题描述】:

我正在尝试在UserUser 之间建立多对多关系,其中用户有很多关注者,也有很多关注者。

我通过一个名为 Follow 的模型创建了一个数据透视表,这是迁移文件:

class CreateFollows < ActiveRecord::Migration
  def change
    create_table :follows do |t|
      t.integer :follower_id, index: true
      t.integer :followed_id, index: true

      t.timestamps null: false
    end
  add_index :follows, [ :follower_id, :followed_id ], unique: true
  end
end

但是,我无法定义 has_many。我试过这样做:

user.rb:

has_many :followers, foreign_key: "followed_id", class_name: "Follow"
has_many :followed, foreign_key: "follower_id", class_name: "Follow"

follow.rb:

class Follow < ActiveRecord::Base
    belongs_to :followed, class_name: "User"
    belongs_to :follower, class_name: "User"
end

但是,当尝试像 @user.followers &lt;&lt; @user_to_be_followed 这样尝试将用户添加到关注者或关注的集合时,我收到一个类型错误,提示应该是 Follow,而不是 User。有道理。

但是我如何定义has_many 说模型应该是User 但外键按定义调用并且表是follows

我怎样才能做到这一点?

编辑搜索我偶然发现this 看起来我这样做的方式是正确的......

【问题讨论】:

  • 你考虑过使用acts_as_follower
  • 我不知道那个。但是要知道,我已经付出了我想以我正在尝试的方式去做的努力。尤其是当它看起来我做得对时

标签: ruby-on-rails ruby-on-rails-4


【解决方案1】:

请注意,我已将 Follow 更改为 Subscription。 Follow 是动词而不是名词,这使得它作为模型名称非常尴尬。

使用 has_many 时,尽管您都必须设置与连接模型的关系和 has_many through: :join_relation 才能获得与另一个模型的直接关系。这种情况有点特殊,因为 User 与 Subscription 有双重关系。

class Subscription < ActiveRecord::Base
  belongs_to :follower, class_name: 'User'
  belongs_to :followed, class_name: 'User'
end

class User < ActiveRecord::Base
  # This looks kind of weird but we have to tell Rails how to find the
  # correct foreign_key for both of the relation types
  has_many :subscriptions,
    foreign_key: :follower_id

  has_many :subscriptions_as_followed,
    class_name: 'Subscription',
    foreign_key: :followed_id

  has_many :followed,
    class_name: 'User',
    through: :subscriptions,
    source: :followed

  has_many :followers,
    class_name: 'User',
    through: :subscriptions_as_followed,
    source: :follower

  # Subscribes to another user
  def follow!(other_user)
    subscriptions.find_or_create_by(followed: other_user)
  end
end

【讨论】:

  • other question you linked to 仅设置与连接模型的关系。你必须做user.following.first.user,这太荒谬了。我们可以做得更好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-11
  • 2014-01-06
  • 1970-01-01
  • 1970-01-01
  • 2016-11-23
相关资源
最近更新 更多