Ruby on rails Rails 4:设置多对多(跟随者和跟随者)
我试图在Ruby on rails Rails 4:设置多对多(跟随者和跟随者),ruby-on-rails,ruby-on-rails-4,Ruby On Rails,Ruby On Rails 4,我试图在用户和用户之间建立一种多对多关系,在这种关系中,用户有很多追随者,也有很多追随者 我通过名为Follow的模型创建了一个透视表,这是迁移文件: class CreateFollows < ActiveRecord::Migration def change create_table :follows do |t| t.integer :follower_id, index: true t.integer :followed_id, index:
用户
和用户
之间建立一种多对多关系,在这种关系中,用户有很多追随者,也有很多追随者
我通过名为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
follow.rb
:
has_many :followers, foreign_key: "followed_id", class_name: "Follow"
has_many :followed, foreign_key: "follower_id", class_name: "Follow"
class Follow < ActiveRecord::Base
belongs_to :followed, class_name: "User"
belongs_to :follower, class_name: "User"
end
class Follow
但是,当尝试将用户添加到followers或followers集合时,例如@user.followers
请注意,我已将Follow
更改为Subscription
。Follow是一个动词,而不是一个名词,这使得它作为一个模型名非常尴尬
当使用has\u many时,尽管双方都必须设置与联接模型的关系,并且ahas\u many through::join\u relation
可以获得与另一个模型的直接关系。这种情况有点特殊,因为用户与订阅有双重关系
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
类订阅
您考虑过使用吗?我不知道。但是要知道,我已经尽了我的努力,我想用我正在努力的方式去做。特别是当它看起来像我做得对的时候,它只建立了与连接模型的关系。您必须执行user.following.first.user
,这是很好的。我们可以做得更好。