mustERkennung

mustERkennung … stuff about patterns and their recognition

Ruby and me – III

leave a comment »

There are valuable ressources to be found in the internet. Some of them are:

But I was lost when it came to the implementation of a link table. Not the implementation itself but the implementation of the ActiveRecord associations for later usage.

I have a data model containing (beside others) one RELATIONS table and one ITEMS table. RELATIONS holds its own ID, and SOURCE and TARGET, both pointing to ITEMS. ITEMS also has its own ID.

From the item perspective I want to know whicht items are pointing to me, and to which items I’m pointing to. Just get the world around the item. The difficulty is that I left Rubys path of conversions here and need to name everything on my own. What needs to be done (without any :destroy or other surounding codes) is:

  1. Create a association “links_to_sources” to all the RELATIONS pointing to me
  2. Use this association to access all the ITEMS pointing to me
  3. Do the same for the other direction: Create a association “link_to_targets” to all the RELATIONS I’m pointing to and use this association to access all the ITEMS I’m pointing to

The overall code (in item.rb, the ITEM model) does look like this:

has_many :links_to_sources, :class_name => "Relation", :foreign_key => "target"
has_many :sources, :class_name => "Item", :through => :links_to_sources, :source => :predecessor
has_many :links_to_targets, :class_name => "Relation", :foreign_key => "source"
has_many :targets, :class_name => "Item", :through => :links_to_targets, :source => :successor

What was not clear to me from all the documentations was the meaning of :source” configuration and the importance of the counterpart, in this example the RELATIONS model (relations.rb). Here its this code:

belongs_to :predecessor, :class_name => "Poem", :foreign_key => "source"
belongs_to :successor, :class_name => "Poem", :foreign_key => "target"

It is neccessary to reuse the name of the belongs_to association (RELATIONS model) as reference for the :source option in the has_many association of the ITEMS model. That the same foreign keys are used is clear as this is predefined by the data model.

What now? I’m able to access all item I’m pointing to simply by using

self.targets

and any iterator afterwards. And this by implementing no code on my own but using the features of ActiveRecord.

Written by Rayk Fenske

January 8, 2012 at 5:19 pm

Posted in Uncategorized

Tagged with , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: