1

我正在尝试将一个人的 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?

友谊.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
4

1 回答 1

4

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
于 2013-02-21T05:04:33.503 回答