klasarn
klasarn

Reputation: 129

Rails 5: Combining two ActiveRecord Models

I'm currently trying to display the users that where invited by the current user and I also want to display the last reservation the made, if they made one.

My Users Controller:

@users = User.where(invited_by_id: current_user.id)

My View:

<% @users.each do |user| %>
<%= user.fullname %> #Works
<%= user.invited_by.fullname %> #Works
<% end %>

What I've already tried:

<% @users.each do |user| %>
<% user.reservations.each do |reservation| %>
<%= reservation.user.fullname %> #Works
<%= reservation.price %> # Works
<% end %>
<% end %>

But this gives me all reservations a user made, I only want the first reservation from the user and therefore only one table for each user.

Is it possible to achieve this in the view or do I need to make some changes in my controller ?

Upvotes: 0

Views: 32

Answers (1)

widjajayd
widjajayd

Reputation: 6253

since you only need first reservation from each user, the custom associations (has_one) below can help your query in controller

User.rb

class User < ActiveRecord::Base
  has_many :reservations
  has_one  :first_reservation, -> { order('created_at ASC')}, class_name: "Reservation"
end

User Controller:

@users = User.where(invited_by_id: current_user.id).preload(:first_reservation)
# preload will make sure load the reservation record as well to prevent n+1 

your view combined user and first reservation, since you already setup has_one, you can call user.first_reservation

<% @users.each do |user| %>
  <%= user.fullname %> 
  <%= user.first_reservation.price %> 
<% end %>

Upvotes: 3

Related Questions