Hi everyone,
I ran into a serious problem when I was trying to do something similar
to twitter follow mechanism. The thing is like this:
First, I have a self-referential table, named “users”
create_table :users do |t|
t.column :name, :string
t.column :user_name, :string
t.column :password, :string
t.column :email, :string
end
I also have a HABTM join table, named “follow_relations”
create_table :follow_realtions do |t|
t.column :a_id, :integer # a_id follows b_id
t.column :b_id, :integer
end
My HABTM join is defined as follows
has_and_belongs_to_many :followers,
:class_name =>
“User”,
:join_table =>
“follow_relations”,
:foreign_key =>
“b_id”,
:association_foreign_key
=> “a_id”
has_and_belongs_to_many :followings,
:class_name => “User”,
:join_table =>
“follow_relations”,
:foreign_key =>
“a_id”,
:association_foreign_key
=> “b_id”
When I executed:
gaoxh = User.create(:name => “gaoxh”)
micai = User.create(:name => “micai”)
xiexin = User.create(:name => “xiexin”)
gaoxh.followers << micai
xiexin.followers << micai
The first << operation executes the following SQL :
INSERT INTO follow_relations (
id,
b_id,
a_id) VALUES (3, 1, 3) The second << operation executes the following SQL: INSERT INTO
follow_relations (id
, b_id
, a_id
) VALUES (3, 2, 3)
Thus, key id is duplicated. It looks like that every time, the value
of column id is copied from column a_id.
What’s going on here? How to fix this problem?
Thanks in advance,
xiahong