Search code examples
ruby-on-railsdatabasehas-and-belongs-to-manythesaurus

Thesaurus in Rails 3


I am using Rails 3 and I would like to create an application that works like a thesaurus. I have read some tutorials on how to do has-and-belongs-to-many (HABTM) relationships, but I'm not sure how to configure my models such that one "item" has and belongs to many other items, i.e. its synonyms.

I suppose what I'm trying to do is a bit like a "related posts" section in a blog, where at the back-end each post must have several "related posts".


Solution

  • I'd look at this as a many-to-many relationship where you need a separate model to handle the relationship.

    class Word < ActiveRecord::Base
      has_many :source_words, :class_name=>"WordLink", :foreign_key=>:source_word_id
      has_many :linked_words, :class_name=>"WordLink", :foreign_key=>:linked_word_id
    
    class WordLink < ActiveRecord::Base
      belongs_to :source_word, :class_name=>"Word"
      belongs_to :linked_word, :class_name=>"word"
    

    Then you'd just need to do something like this to create / display words & synonyms:

    w = Word.create(:word_name=>"Cold")
    w.source_words.create(:linked_word=>Word.create(:word_name=>"Icy"))
    
    synonyms_as_text_array = w.source_words.collect {|s| s.linked_word.word_name }