Reputation: 618
New working with Rails 4 and have a question on associations.
Let's say I have a Car
create_table "cars", force: true do |t|
t.string "name"
t.integer "owner_id"
t.integer "mechanic_id"
end
And I have some users which roles are "Owner" and "Mechanic"
create_table "users", force: true do |t|
t.string "name"
t.integer "role_id"
end
Now when I get a list of Cars, I want the names of the Owner and the Mechanic...
I know this sounds easy but i've been banging my head around the associations and not getting anywhere.
I want to display this:
name owner mechanic
Ferari Paul James
with this schema
User
id first role
1 Paul owner
2 James mechanic
Car
name owner_id mechanic_id
Ferrari 1 2
Any help would be much appreciated.
Upvotes: 2
Views: 71
Reputation: 8668
You have two associations to the same model. So in your model/car.rb
write:
class Car < ActiveRecord::Base
belongs_to :owner, class_name: 'User'
belongs_to :mechanic, class_name: 'User'
end
and you can use car.owner.name
and car.mechanic.name
.
See rails guide on associations
Upvotes: 2