Ruby on Rails与自我有很多很多关系

时间:2013-02-21 04:55:45

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

我正在尝试将一个人的Facebook好友保存到我的数据库中。我想将Facebook用户存储在一个表中,然后将他们的友谊存储在另一个表中。友谊将具有请求友谊的FacebookUser的整数和朋友的整数,两者都是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?

friendship.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

1 个答案:

答案 0 :(得分:3)

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