Ruby-on-rails – Rails model with foreign_key and link table

foreign-keysmodelruby-on-rails

I am trying to create a model for a ruby on rails project that builds relationships between different words. Think of it as a dictionary where the "Links" between two words shows that they can be used synonymously. My DB looks something like this:

Words
----
id

Links
-----
id
word1_id
word2_id

How do I create a relationship between two words, using the link-table. I've tried to create the model but was not sure how to get the link-table into play:

class Word < ActiveRecord::Base
  has_many :synonyms, :class_name => 'Word', :foreign_key => 'word1_id'
end

Best Answer

In general, if your association has suffixes such as 1 and 2, it's not set up properly. Try this for the Word model:

class Word < ActiveRecord::Base
  has_many :links, :dependent => :destroy
  has_many :synonyms, :through => :links
end

Link model:

class Link < ActiveRecord::Base
  belongs_to :word
  belongs_to :synonym, :class_name => 'Word'

  # Creates the complementary link automatically - this means all synonymous
  # relationships are represented in @word.synonyms
  def after_save_on_create
    if find_complement.nil?
      Link.new(:word => synonym, :synonym => word).save
    end
  end

  # Deletes the complementary link automatically.
  def after_destroy
    if complement = find_complement
      complement.destroy
    end
  end

  protected

  def find_complement
    Link.find(:first, :conditions => 
      ["word_id = ? and synonym_id = ?", synonym.id, word.id])
  end
end

Tables:

Words
----
id

Links
-----
id
word_id
synonym_id
Related Topic