Thank you both for the suggestions and for the pointer to your blog!
Yep, my approach was and is still gross, but I must admit I am concerned
with the size that the join table will take, as currently the urls table
has about 7000 records and the phrases table has about 87000 records…
So, being a newbie with the has_many :through relationship I’d like to
make sure I understand before commiting to its implementation. A quick
rundown to make sure I am getting what I need to do, please tear this
apart if it becomes apparent that I missed the boat – used the example
from hasmanythrough.com.
Table 1: urls - has id and url
Table 2: phrases - has id and phrase
Table 3: relations - has id, url_id, phrase_id, isrelevant (boolean)
Ignore isrelevant for now as I can add class methods to weed out the
relationship during overloaded finds, am mostly concerned in the url ↔
phrases relationship.
class Relation < ActiveRecord::Base
belongs_to :url, :foreign_key => “url_id”, :class_name => “Url”
belongs_to :phrase, :foreign_key => “phrase_id”, :class_name =>
“Phrase”
end
class Url < ActiveRecord::Base
has_many :related_as_phrase, :foreign_key => ‘phrase_id’,
:class_name => ‘Relation’
has_many :phrases, :through => :related_as_phrase
end
class Phrase < ActiveRecord::Base
has_many :related_as_url, :foreign_key => ‘url_id’,
:class_name => ‘Relation’
has_many :urls, :through => :related_as_urls
end
Do the above model rules look right for this? Anything I should be aware
of?
Thanks again, am much appeciated that this was pointed out to me!
-Andy
Wow, that sounds gross. Packing foreign keys into a varchar list of ids
means you lose all the power of the database to create relations between
records or do queries with joins. You get more leverage from using
something like a join table to let the database manage those relations
for you. There are two ways to do what you want, has_and_belong_to_many
(join table) or has_many :through (join model). If you go with habtm
you’ll need two join tables, one for each type of relationship. If you
use has_many :through, you can use one join model with an attribute that
indicates the type of the relationship. You can find a lot more
information about doing that on my blog.
–
Josh S.
http://blog.hasmanythrough.com