Rails :through

June 6th, 2006 -

Nate, over at the Godbit forum had asked a question some time ago about using Rails to join tables. His assessment was that there aren’t very many good tutorials on the subject. So, I present to you a very simple Rails tutorial covering how you would join tables.

To begin, let’s assume you have three tables in your database. They are called orders, line items, products. These are our hypothetical columns within the tables:

orders

  • id
  • name

line_items

  • id
  • products_id
  • orders_id
  • amount

products

  • id
  • name

Currently, every order has line items and line items are associated with a product. Basic stuff that you may or may not have read in the Agile Web Dev with Rails book.

The problem that we want to solve is allowing products to be associated with orders. First, we need to go to our Model.


class Product < ActiveRecord::Base
  has_many :orders, :through => line_items
end

The key to making tables join is the :through declaration. Think of it this way, Product has many orders and is going through line_items to get those orders. It needs to go through line_items in order (not our table) to get the id associated with the order.

Rails then handles the joining of the tables. Now, you can do the following statements:


product = Product.find(id)
our_orders = product.orders


I hope this gives you a better understanding of the :through declaration and how simple and powerful it is.

Tags: rails, ruby

 

Comments

 

Commenting has been turned off.