友谊自我指涉协会

时间:2017-10-14 15:18:27

标签: ruby-on-rails self-join self-referencing-table

我一直在尝试实施Facebook风格的朋友系统。我已经阅读了几个教程,无法理解我做错了什么。友情控制器和视图中的链接用于添加好友工作,但在数据库级别它会抛出错误。

当我打开rails控制台并放入:

User.find(1).friends << User.find(2)

我明白了:

SQL (0.4ms)  INSERT INTO "friendships" ("user_id", "friend_id", "created_at", "updated_at") VALUES (?, ?, ?, ?)  [["user_id", 1], ["friend_id", 2], ["created_at", "2017-10-14 15:01:28.364691"], ["updated_at", "2017-10-14 15:01:28.364691"]]
(0.1ms)  rollback transaction
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such table: main.friends: INSERT INTO "friendships" ("user_id", "friend_id", "created_at", "updated_at") VALUES (?, ?, ?, ?)
from (irb):1

user.rb

has_many :friendships, dependent: :destroy
has_many :friends, through: :friendships

# these are used in the controller

def befriend(user)
  friends << user
end

def unfriend(user)
  friends.delete(user)
end

def friends?(user)
  friends.include?(user)
end

friendship.rb

belongs_to :user
belongs_to :friend, class_name: 'User', foreign_key: "friend_id"

validates :user_id, presence: true
validates :friend_id, presence: true

我正在使用Devise进行身份验证。

2 个答案:

答案 0 :(得分:0)

您不是在创建朋友(其他用户已经存在),但是友谊

user.rb

class User < ActiveRecord::Base
  has_many :friendships, dependent: :destroy
  has_many :friends, through: :friendships, source: :friend
end

friendship.rb

class Friendship < ActiveRecord::Base
  belongs_to :user
  belongs_to :friend, class_name: 'User'
end

控制台

User.find(1).friendship.create(friend_id: User.find(2).id)

答案 1 :(得分:0)

我创建了两个名为User and Friendship的表

> rails g model User first_name:string last_name:string
> rails g model Friendship user:references friend:references
> rake db:migrate

user.db 中,定义了两个has_many关联:

class User < ApplicationRecord
    has_many :friendships, dependent: :destroy
    has_many :friends, through: :friendships
end

friendship.rb 中:

class Friendship < ApplicationRecord
   belongs_to :user
   belongs_to :friend, class_name: 'User'
end

在Rails控制台中,我创建了两个示例用户并使其成为朋友:

> User.create(first_name:"Blue", last_name:"Sky")
> User.create(first_name:"White", last_name:"Cloud")
> Friendship.create(user:User.first, friend:User.second)
> Friendship.create(user:User.second, friend:User.first)

或者:

> User.first.friendships.create(friend:User.second)
> User.second.friendships.create(friend:User.first)

现在,您可以检索属于一个用户的所有朋友。例如:

> User.first.friends