Dylan Russell
Dylan Russell

Reputation: 11

Ruby on Rails, taking information from multiple tables to display in view

So tasking.point_of_contact is an integer value that is the same number as the user.id whose name (name is defined as :firstname + :lastname) I want to display.

How can I take the value in tasking.point_of_contact and use it to call the name of the corresponding user.id?

Right now I have:

<td><%= tasking.point_of_contact %></td>

I want that to display the name of the user whose user.id equals tasking.point_of_contact.

The relationship between user and taskings is a many-to-many.

I hope I've give you enough information. I may have been redundant, but I just want to be clear.

Upvotes: 0

Views: 178

Answers (2)

hd1
hd1

Reputation: 34657

There are some helper methods generated automatically when you have a has_and_belongs_to_many relationship. Specifically, the others generated method should be helpful. In your case, it would be tasking.users. However, I'm not sure your design is correct...

Upvotes: 0

JoshEmory
JoshEmory

Reputation: 644

If you haven't set up your relationship in your tasking model yet, you want to do that.

belongs_to :user, :class_name => "User", :foreign_key => "point_of_contact"

Then, where ever you're doing the initial query

@tasking = Tasking.where(whatever)

You'll want to eager load the users so you don't get a N+1 issue (you can google this, just an efficiency thing).

@tasking = Tasking.includes(:user).where(whatever you want to find)

Then in your view you'll do

tasking.user.name

Upvotes: 3

Related Questions