views:

32

answers:

1
+1  Q: 

has_many in rails

I have a 'users' table which stores all of my websites users, some of which are technicians. The users table has a 'first_name' and 'last_name' field as well as other fields.

The other table is called 'service_tickets' which has a foreign key from users called technician_id. This gives me a real problem because when I am looking at the service_tickets table, the related user is actually a technician. That's why the service_tickets table has a technician_id and not a user_id field.

I am trying to accomplish something like this:

t = service_ticket.find_by_id(7)
t.technician.first_name        # notice how I don't do t.user.first_name

Is this possible in rails? I can't seem to get it to work...

Thank you for your help!

+2  A: 

In your service ticket model, you can add a technician relationship like...

belongs_to :technician, :class_name => "User"

It will use the User model in this case for the technician_id

Beerlington
Thanks for the quick reply, unfortunately when I entered the suggested constraint into my model, then typed the following code into my view: <% @service_tickets.each do |s| %> <%= s.technician.first_name %> <% end %>I get the following error: "undefined method `first_name' for nil:NilClass"Any ideas what this could be? Do I have to put anything other than "has_many :service_tickets" in the user model?
By the way, the user model does have a field called 'first_name' in it.
After rebooting the server, your code worked! Never mind on my previous posts. Thank you!By the way, I put a :foreign_key setting on the end which I read about online like this: belongs_to :technician, :class_name => "User", :foreign_key => "technician_id"Is that okay?
You shouldn't need to add the `foreign_key` option unless belongs_to "xxx" is different than what you call it in the foreign key table. In your case, using `belongs_to :technician` expects a a field in the service ticket called technician_id. If you were to call it something like "tech_id" in the service ticket table, then you would have needed :foreign_key => "tech_id". See http://rails.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#M001318 for more.
Beerlington