Many-to-many self-referential connection

Hi, folks!

I’m trying to model the following kind of relationship in my
application:

Each Topic has many related Topics. The relationship is characterised
by “similarity” parameter.

That’s what I have in DB:

create_table “topics” do |t|
t.column “name” :string
end

create_table “related_topics” do |t|
t.column “topic_id”, :integer, :null => false
t.column “related_topic_id”, :integer, :null => false
t.column “similarity” :integer
end

and in the model:

class Topic < ActiveRecord::Base
has_and_belongs_to_many :related_topics,
:class_name => “Topic”,
:join_table => “related_topics”,
:association_foreign_key => “related_topic_id”,
:foreign_key => “topic_id”

What is bad about this reference is that the similarity parameter is
unaccessible!
I can’t affect it neither during <<'ing of related_topics, or any other
way.

E.g. when I do:
tp = Topic.find(1)
tp.related_topics.find(1).similarity = 5
tp.save

the similarity does not save.

I guess I should use join models and :through, but I have no idea how
to access similarity parameter in that case as well.

Please point me at any solutions to the problem. Thank you.

this sounds like a job for a “has_many :through =>” association

read this blog post on self-referential has_many :through associations,
i think its quite exactly what you need. This blog covers other
related_topics ( lol ) about this as well, have fun

http://blog.hasmanythrough.com/articles/2006/04/21/self-referential-through

Thorsten, thanks for your answer.
I’ve tried this approach, but I can’t modify the “similarity” parameter
anyway.

If you look, Josh also has a “flow” parameter for his graphs - it’s
exactly the same (in terms of db organization), what I want. But
unfortunately, he writes nothing about flow’s further fate.

So, still looking for the solution.