2013-02-21 94 views
1

我試圖將一個人的Facebook朋友保存到我的數據庫中。我想將Facebook用戶存儲在一個表中,然後將他們的友誼存儲在另一個表中。友誼將具有請求友誼的FacebookUser的整數和朋友的整數,這兩者都是facebook_users表的外鍵。但是,當我嘗試將用戶的Facebook朋友與友情鏈接時,我不斷收到此消息。Ruby on Rails與自己的多對多關係

錯誤

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 

Schema

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 

回答

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