Reputation: 129
I'm trying to view all reservations a user has made. I still require a page with all reservations available for other users of the system. I've set up another page called bookings with a controller to try and view only the users reservations. I've tried to have a look at other questions but haven't been able to solve this.
currently in my bookings controller I have
def index
@user = User.find(session[:user_id])
@reservations = Reservation.find_by_id(@user)
end
In my views booking index.html.erb I have
<h1> Viewing All Reservations </h1>
<table class="table table-striped">
<thead>
<tr>
<th>ID</th>
<th>Vehicle ID</th>
<th>User ID</th>
<th>Start Date</th>
<th>End Date</th>
<th>Costs</th>
</tr>
</thead>
<tbody>
<% @reservations.each do |reservation| %>
<tr>
<td><%= reservation.id %></td>
<td><%= reservation.user_id %></td>
<td><%= reservation.vehicle_id %></td>
<td><%= reservation.startDate %></td>
<td><%= reservation.endDate %></td>
<td><%= reservation.costs %></td>
</tr>
<% end %>
</tbody>
</table>
Please let me know where I'm going wrong.
Upvotes: 0
Views: 246
Reputation: 3005
find_by
only returns one record. You should use where
def index
@user = User.find(session[:user_id])
@reservations = Reservation.where(user_id: @user.id)
end
You could use the association records (assuming a User has_many :reservations
.
def index
@user = User.find(session[:user_id])
@reservations = @user.reservations
end
If you want the same the same method to show your reservations or all reservations, you can add a param
def index
if params[:all]
@reservations = Reservation.all
else
@user = User.find(session[:user_id])
@reservations = @user.reservations
end
end
Upvotes: 3