Stefan Bossbaly
Stefan Bossbaly

Reputation: 6804

Ruby on Rails Many to Many Relationship with Self

I am trying to save a person's Facebook friends into my database. I want to store the Facebook users in a table and then store their friendships in another table. The friendships would have the integer of the FacebookUser that requested the friendship and the integer of the friend, both of which are foreign keys to the facebook_users table. However I keep getting this message when I try to link the a user's facebook friends with friendships.

Error

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

Upvotes: 1

Views: 835

Answers (1)

jvnill
jvnill

Reputation: 29599

the convention Rails uses is to use associations as defined by the class name and the foreign key. if you've set up your tables like above, you should change your models to the following.

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

Upvotes: 4

Related Questions