Old 25-07-2006, 04:52   #1 (permalink)
cam
vague™
 
cam's Avatar
 
Join Date: Mar 2004
Location: Glasgow
Posts: 5,337
Rails joining

Hey, quick question regarding joining while using ActiveRecord's find method:

If i have the following models setup:

Course
- has_many :course_dates

CourseDate
- belongs_to :course
- has_one :venue

Venue
- belongs_to :course_date

Is there any way to get Rails to automatically join all three tables using find without having to explicitly write the SQL join syntax? The following will work, but I can't see any way to connect the venue table as well (which is related to course dates, not the course itself).

Quote:
# Return any special offers
def special_offers
@special_offers = Course.find(
:all,
:select => "courses.id, courses.name",
:include => [:course_dates],
:conditions => ["courses.active = true AND courses.special = false"])
end

Cheers for any help - just thought I'd ask before resorting to writing the SQL.
__________________
Random goodness at The Blog

  Reply With Quote
Old 25-07-2006, 06:34   #2 (permalink)
Luke Redpath
Barney army!
 
Luke Redpath's Avatar
 
Join Date: Mar 2003
Location: London
Posts: 696
Well, with a normal find, there isn't anything stopping you from doing the following to get at a venue:

Code:
some_course.course_data.venue

So I assume you are trying to do some kind of eager loading to reduce the number of queries?

You could try this change to your course model:

Code:
class Course < ActiveRecord::Base has_many :course_dates, :include => :venue

Then when loading courses, specify :include => :course_dates as normal.
__________________
Luke Redpath .::. Software Engineer .::. Reevoo - Real Reviews From Real Customers
  Reply With Quote
Old 25-07-2006, 06:42   #3 (permalink)
cam
vague™
 
cam's Avatar
 
Join Date: Mar 2004
Location: Glasgow
Posts: 5,337
Hi Luke, cheers for the reply. Yes, I'm trying to reduce the number of queries necessary. Tried the change you suggested but it didn't seem to have the desired effect. Having the join written explicitly isn't too big a deal, so i'll use that for now.

Quote:
Originally Posted by Luke Redpath
Well, with a normal find, there isn't anything stopping you from doing the following to get at a venue:

Code:
some_course.course_data.venue

So I assume you are trying to do some kind of eager loading to reduce the number of queries?

You could try this change to your course model:

Code:
class Course < ActiveRecord::Base has_many :course_dates, :include => :venue

Then when loading courses, specify :include => :course_dates as normal.
__________________
Random goodness at The Blog

  Reply With Quote
Reply



Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools Search this Thread
Search this Thread:

Advanced Search


Contact Us - Web Design Forums - Archive - Top
Search Engine Optimization by vBSEO 3.0.0 RC8