proofexak
proofexak

Reputation: 57

undefined method after using includes

i'll start how my models looks:

User -> has_one :customer, has_one :employee, has_many :appointments
Customer -> belongs_to :user
Employee -> belongs_to :user
Appointment -> belongs_to :user

And now in view:

<% @appointments.order(:appointment_date).each do |appointment| %>
            <% if appointment.confirmation == wait_or_confirmed?(@status) %>
              <tr>
                <td><%= appointment.purpose %></td>
                <td><%= appointment.appointment_date %></td>
                <td><%= appointment.appointment_time %></td>
                <td><%= Employee.find(appointment.employee_id).first_name %>  <%= Employee.find(appointment.employee_id).last_name %></td>
                <td><%= Customer.find(appointment.customer_id).first_name %>  <%= Customer.find(appointment.customer_id).last_name %></td>
                <td><%= link_to 'Show', appointment_path(appointment), class: "btn btn-primary" %></td>
              </tr>
            <% end %>
          <% end %>

My brother told me i shouldnt pick up informtaions from database in views so i tried using includes:

@appointments = Appointment.all
@users = User.includes(:appointments)

And after combination in view it still doesn't work. Can someone help me?

Upvotes: 1

Views: 579

Answers (1)

Tom Lord
Tom Lord

Reputation: 28305

Instead of this:

Employee.find(appointment.employee_id).first_name

Do this:

appointment.employee.first_name

For performance, in the controller, you can also replace this:

@appointments = Appointment.all

With this:

@appointments = Appointment.all.includes(:employee, :customer)

By doing so, you are eager-loading all associated employee and customer data from the database in a single query, rather than one at a time.

Upvotes: 2

Related Questions