Paco Vermeulen
Paco Vermeulen

Reputation: 120

Access attribute from other model in Rails

I am a Rails beginner building my first web app.

At the moment I have two models: Users and Patients. A User has_many patients and a Patient belongs_to a User. In the Patients controller I added the following line to the create action to show only the Patients that belong to the logged in User in patients#index.

@patient.user_id = current_user.id 

In the table on patients#index it shows the user_id

<td><%= patient.user_id %></td>

The User model has a company_name:string attribute.

How can I show the :company_name from my User model on this page - instead of the user_id?

Upvotes: 1

Views: 631

Answers (2)

Richard Peck
Richard Peck

Reputation: 76774

Law Of Dementer

Further to Marek's answer, you may wish to look into the delegate method

I don't know for sure whether this will help you directly, as delegate only works with belongs_to and has_one methods (although I've got it working tentatively with has_many before)

--

#app/models/patient.rb
Class Patient < ActiveRecord::Base
   belongs_to :user
   delegate :company_name, to: :user, prefix: true
end

This will allow you to call:

<%= patient.user_company_name %>

More cosmetic than anything - but always handy to have, considering you can have so many associations all over the place

Upvotes: 1

Marek Lipka
Marek Lipka

Reputation: 51151

You should make use of your user association:

<td><%= patient.user.company_name %></td>

Upvotes: 2

Related Questions