Hi, I have a Project model, and a Party model (as in people, not celebrations ;). Parties can have one or more Roles, like so: class Party < ActiveRecord::Base has_and_belongs_to_many :roles end I have the appropriate join table (parties_roles) to facilitate this, as well as a call to habtm in the Role model. The Project model references (using belongs_to) four parties, all having different roles, like so: class Project < ActiveRecord::Base belongs_to :primary_contact, :class_name => "Party" belongs_to :liaison, :class_name => "Party" belongs_to :data_source, :class_name => "Party" belongs_to :applicant, :class_name => "Party" end I have a project fixture like the following (fields omitted for brevity): first_project: id: 1 name: 01-234 data_source: 4 And a party fixture: data_source: id: 4 first_name: James last_name: Hughes In project_test.rb: def test_associations assert_equal @project.name, ''01-234'' assert_equal @project.data_source.last_name, ''Hughes'' end The first assertion passes; the second fails with, "NoMethodError: undefined method `last_name'' for nil:NilClass. " What am I missing? Thanks! ps. I''m loading fixtures in the project test file as follows: fixtures :projects, :parties, :parties_roles, :roles -- James Hughes Web application developer Centre for Health Services and Policy Research Vancouver, BC
James Hughes
2005-Sep-21 17:11 UTC
Re: habtm, fixtures, typical troubles with associations..
On 9/20/05, James Hughes <hughes.james-Re5JQEeQqe8AvxtiuMwx3w@public.gmane.org> wrote:> Hi, > > I have a Project model, and a Party model (as in people, not > celebrations ;). Parties can have one or more Roles, like so: > > class Party < ActiveRecord::Base > has_and_belongs_to_many :roles > end > > I have the appropriate join table (parties_roles) to facilitate this, > as well as a call to habtm in the Role model. > > The Project model references (using belongs_to) four parties, all > having different roles, like so: > > class Project < ActiveRecord::Base > belongs_to :primary_contact, :class_name => "Party" > belongs_to :liaison, :class_name => "Party" > belongs_to :data_source, :class_name => "Party" > belongs_to :applicant, :class_name => "Party" > endWell, I guess I might as well post my solution, for future generations. Adding the :foreign_key option did the trick: belongs_to :primary_contact, :class_name => "Party", :foreign_key => "primary_contact" Not sure why I thought I could get away without that... J -- James Hughes Web application developer Centre for Health Services and Policy Research Vancouver, BC