Has_many, through to has_many

I have a situation where I need to get Courses for a particular User.
Courses are associated with Divisions that in turn are related to the
user
by a has_many, through relationship. Ideally, I’d like to stay within
the
framework and do something like this:

@courses = @user.divisions.courses

Or if I’m looking for a particular course I could do this:

@course = @user.divisions.courses.find(Params[:id])

Is this completely outside of the framework?

Here is the model setup I have:

end

I managed to get a list of all Courses by adding a function in the User
model, but this isn’t ideal for a few reasons, the most important being
if I
only need to find one Course, I’m forced to retrieve all of the courses
and
then perform an @courses.select{yada yada}. There must be a Better
Way™! Any ideas?

class User < ActiveRecord::Base

I’m assuming you know the ID of the course you want to select.

Why don’t you just do

Course.find(params[:id])

instead of:

@course = @user.divisions.courses.find(Params[:id])

On Dec 7, 2007 1:58 AM, Joe C. [email protected] wrote:

@course = @user.divisions.courses.find(Params[:id])

has_many :courses
only need to find one Course, I’m forced to retrieve all of the courses and
self.divisions.each do |division|


Ryan B.

Hey, thanks for the reply.

It’s a validation check to make sure that the url isn’t spoofed by the
user. We don’t want one user editing a course that isn’t associated to
them:
www.example.com/course/edit/6

Changed to
www.example.com/course/edit/16

Joe C. wrote:

Hey, thanks for the reply.

It’s a validation check to make sure that the url isn’t spoofed by the
user. We don’t want one user editing a course that isn’t associated to
them:
www.example.com/course/edit/6

Changed to
www.example.com/course/edit/16

fine, take all my fun away.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs