views:

44

answers:

2

I have three classes with the following associations:

class Technician < ActiveRecord::Base  
  has_many :tickets
  has_many :services, :through => :tickets  
end

class Ticket < ActiveRecord::Base
  belongs_to :technician
  has_many :services
end

class Service < ActiveRecord::Base
  belongs_to :ticket
  belongs_to :technicians
end

When I try to use the associations in IRB I get the error messages below:

tech = Technician.first
ticket1 = Ticket.new
tech.ticket1

NoMethodError: undefined method `t1' for #<Technician:0xa0d6d6c>
from /usr/local/ruby/lib/ruby/gems/1.9.1/gems/activemodel-3.0.0/lib/active_model/attribute_methods.rb:364:in `method_missing'
from /usr/local/ruby/lib/ruby/gems/1.9.1/gems/activerecord-3.0.0/lib/active_record/attribute_methods.rb:46:in `method_missing'
from (irb):7
from /usr/local/ruby/lib/ruby/gems/1.9.1/gems/railties-3.0.0/lib/rails/commands/console.rb:44:in `start'
from /usr/local/ruby/lib/ruby/gems/1.9.1/gems/railties-3.0.0/lib/rails/commands/console.rb:8:in `start'
from /usr/local/ruby/lib/ruby/gems/1.9.1/gems/railties-3.0.0/lib/rails/commands.rb:23:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'

Am I mission or doing something wrong?

+2  A: 

Yep, you're doing something wrong. You should read this first: http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html

In this particular case, you probably wanted to do something like this:

tech = Technician.first
tech.tickets << Ticket.new
tech.tickets.last
....
buru
thanks so much...it worked...i read through the api but couldn't see how you would actually use the associations. thanks for the reply
anthony
A: 

I'm thinking the modeling of the relationships might be off. This is how I would model them:

class Technician < ActiveRecord::Base  
  has_many :tickets
  has_many :services, :through => :tickets  
end

class Ticket < ActiveRecord::Base
  belongs_to :technician
  belongs_to :service
end

class Service < ActiveRecord::Base
  has_many :tickets
  has_many :technicians, :through => :tickets
end

Of course, I don't know the details of your implementation, so this is at best, a guess.

Buru's syntax for using the associations is correct.

Brian