Jonathan Clark
Jonathan Clark

Reputation: 20538

Getting data from all tables in a join query in Rails 3

I want to join tree tables and access the data from ALL of the tables and not only one.

The three tables are called: Page, Text, Image.

I tried with this but it did not work:

@texts = Page.joins([:texts, :images]).where(['pages.id = ?', @page])

The main one is Page which has_many texts and images. I want to do a query and get the data from all of them in one query. How is that possible in Rails 3? I cannot find a good example anywhere, not even in the official guides.

Update

The reason for doing this instead of @page.texts and @page.images is because I can then only print them in "blocks". I want to mix Texts and Images up when printed.

Upvotes: 1

Views: 2931

Answers (3)

Martin
Martin

Reputation: 11336

This is worth a read, and will help to solve your problem:

http://guides.rubyonrails.org/association_basics.html

Upvotes: -1

Leonel Galán
Leonel Galán

Reputation: 7167

Perhaps you could make Text and Image subclasses of a new 'Page Element', so you can establish one relationship between page elements and your page.

On the other side, you can use Page.join(:texts).select('texts.*') and retrieve columns in the texts table as virtual columns of a Page objects (You could have a Page object with only virtual columns of other tables fields, so this solution can get dirty).

Upvotes: 2

Austin Lin
Austin Lin

Reputation: 2564

A few things:

  • Take a look at this page for help with joins. Notice the :include option which will allow you to get all the data in on query for performance's sake. You will still need to acess it though ActiveRecord (see below).

    http://www.railway.at/articles/2008/04/24/database-agnostic-database-ignorant/

  • Do you need all the data in one giant hash/array? If you have associations setup you can simply do:

    @texts = @page.texts and @images= @page.images

Edit: What about this

@pages = Page.all(:include => [:texts, :images])
@pages.sort!{|a,b| a.texts.count <=> b.texts.count}

Documentation: http://ruby-doc.org/core/classes/Array.html#M002186

Upvotes: 0

Related Questions