I have three tables: Case, Attorney and Firm. Case belongs to Attorney
and Attorney Belongs to Firm. I don’t see how I can define that Case
belongs to Firm through Attorney since Attorney is not a join table
(does not reference both). In order to find all cases for a Firm, it
seems I must write a sequence of queries like this:
class FirmsController < ApplicationController
def show
id = params[:id] @attorneys = Attorney.find(:all, :conditions => [“firm_id = ?”, id]) @cases = Case.find(:all, :conditions => [“attorney_id = ?”, @attorneys.id])
end
end
In this sequence however, @cases doesn’t return any case objects. How
might I get this to work?
I have three tables: Case, Attorney and Firm. Case belongs to Attorney
and Attorney Belongs to Firm. I don’t see how I can define that Case
belongs to Firm through Attorney since Attorney is not a join table
(does not reference both). In order to find all cases for a Firm, it
seems I must write a sequence of queries like this:
class FirmsController < ApplicationController
def show
id = params[:id] @attorneys = Attorney.find(:all, :conditions => [“firm_id = ?”, id]) @cases = Case.find(:all, :conditions => [“attorney_id = ?”, @attorneys.id])
end
end
In this sequence however, @cases doesn’t return any case objects. How
might I get this to work?
As others have pointed out, you can use :include to find things. You
might also want to use an asymetric join model.
BTW, @attorneys.id isn’t what you think, in your original code.
You got the Ruby object_id, not the id attribute from ActiveRecord.
This is a major trap, because it sometimes does what you want.
Just ALWAYS write @thing[:id] instead… or build your schemas with
config.active_record.primary_key_prefix_type = :table_name
and suffer the fact that the generators might not all do the right
thing.
Clifford H.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.