unlikely_monkey
unlikely_monkey

Reputation: 183

Getting database values via foreign key in Rails ActiveRecord

I have a list of items that are tagged and I would like to list the tag name next to each item. For example:

My cool list item - "Awesome Tag"

Each list item has one, and only one, tag; tag_id is a foreign key in my list table and it is a required field in my model.

I have been thinking about the ways I could try and do this but am not quite sure on best practices...

  1. Create a @tags class variable with an array of all tags and, for each list item, loop through it to see if the ids match. If they do, display the tag name.

  2. Have a custom method in my list_item model where I loop through the list items and append the tag name to the list object so that I could access it in my view via @list_item.tag_name (I'm not sure if this can even be done this way).

  3. Write a custom SQL query to get the tag name into the active record results. For instance:

    SELECT list.descriptions, tag.name 
    FROM list_items AS list 
    INNER JOIN tags AS tag 
    ON(list.tag_id = tag.id)
    

While it appears to be the most resource friendly, the third option seems like a lot of work for something so basic.

Holler if you'd like any additional information.

Upvotes: 0

Views: 1297

Answers (2)

LeEnno
LeEnno

Reputation: 328

You could also use:

@list_item.tag.name

It doesn't need any extra code, so it's understandable to those who aren't familiar with delegate.

Upvotes: 0

Arun
Arun

Reputation: 885

Use delegate

Add this line in list_item model

delegate :name, :to => :tag, :prefix => true

Now you can access tag name by using

@list_item.tag_name

This is more like to your second option.

See more details about delegate here: http://www.simonecarletti.com/blog/2009/12/inside-ruby-on-rails-delegate/

Upvotes: 1

Related Questions