I’m completely stumped by this. Basically, I’ve got an HABTM self
referential model set up and for some reason the join table is only
saving relationships one way. To illustrate this:
member1 = Member.new
member2 = Member.new
member1.friends[0] = member2
member1.save
member2.friends[0] = member1
member2.save
Both saves return true in the console, but only the first actually is
written to the sqlite join table. I’ve tested a number of more in depth
examples, and in every case, I’m only able to get data saved in one
direction in the join table. For example:
member_id | friend_id
1 2
1 3
2 3
2 1 This won’t save
3 2 This won’t save either
In the console everything shows up correctly if I list .friends for any
object. But after restarting the console, only the uni-directional
entries remain.
Any help would be greatly appreciated! In my project I need to be able
to call .friends on any member and receive all members they are friends
with. Here’s my code:
# Member object
class CreateMembers < ActiveRecord::Migration
def self.up
create_table :members do |t|
t.string :name
t.timestamps
end
end
def self.down
drop_table :members
end
end
# Join table
class CreateMembersFriends < ActiveRecord::Migration
def self.up
create_table :members_friends, :id => false do |t|
t.integer :member_id
t.integer :friend_id
end
end
def self.down
end
end
# Model
class Member < ActiveRecord::Base
has_and_belongs_to_many :friends,
:class_name => “Member”,
:join_table => “members_friends”,
:foreign_key => “member_id”,
:association_foreign_key => “friend_id”
end