ruby-on-rails - Ruby on Rails 与 self 的多对多关系

标签 ruby-on-rails database many-to-many rails-activerecord

我正在尝试将一个人的 Facebook 好友保存到我的数据库中。我想将 Facebook 用户存储在一个表中,然后将他们的友谊存储在另一个表中。友谊将具有请求友谊的 FacebookUser 的整数和 friend 的整数,两者都是 facebook_users 表的外键。但是,当我尝试将用户的 Facebook 好友链接到好友时,我不断收到此消息。

错误

ActiveRecord::HasManyThroughSourceAssociationNotFoundError: Could not find the source association(s) :friend or :friends in model Friendship. Try 'has_many :friends, :through => :friendships, :source 
=> <name>'. Is it one of :FacebookUser or :FacebookFriend?

友谊.rb

class Friendship < ActiveRecord::Base
  attr_accessible :facebook_user_id, :facebook_friend_id

  belongs_to :FacebookUser
  belongs_to :FacebookFriend, :class_name => :FacebookUser
end

facebook_user.rb

class FacebookUser < ActiveRecord::Base
  attr_accessible :first_name, :gender, :last_name

  has_many :friendships, :foreign_key => :facebook_user_id
  has_many :friends, :through => :friendships, :source => :FacebookUser
end

架构

create_table "facebook_users", :force => true do |t|
  t.string   "first_name"
  t.string   "last_name"
  t.string   "gender"
  t.datetime "created_at", :null => false
  t.datetime "updated_at", :null => false
end

create_table "friendships", :force => true do |t|
  t.integer "facebook_user_id"
  t.integer "facebook_friend_id"
end

最佳答案

Rails 使用的约定是使用由类名和外键定义的关联。如果您像上面那样设置了表格,则应将模型更改为以下内容。

class Friendship < ActiveRecord::Base
  attr_accessible :facebook_user_id, :facebook_friend_id

  belongs_to :facebook_user # implies a foreign key of facebook_user_id and class of FacebookUser
  belongs_to :facebook_friend, class_name: 'FacebookUser' #implies a foreign key of facebook_friend_id
end

class FacebookUser < ActiveRecord::Base
  attr_accessible :first_name, :gender, :last_name

  has_many :friendships
  has_many :friends, :through => :friendships, :source => :facebook_friend
end

关于ruby-on-rails - Ruby on Rails 与 self 的多对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14994819/

相关文章:

c# - 设计问题 - 用 C# 更新多行 - 关注多次往返性能

java - 如何使用Netbeans连接JAVA MIDLET到ORACLE/MySQL数据库?

grails - Grails-多对多数据持久性(已编辑)

ruby-on-rails - 如何让一个问题包含另一个对参数的关注

ruby-on-rails - 如何在Windows 7上加速Rails控制台?

数据库交互代码

php - Laravel 与数据透视表关系中的错误

MySQL Rails 迁移错误 : "Error on rename of schema_migration (errno: -1)"

ruby-on-rails - Backbone.js:什么是 paramRoot:backbone.model 中的属性?

java - Hibernate 多对多删除关系