ESoft
ESoft

Reputation: 862

Rails, REST, which controller displays what?

I have a controller which manages Users and a different one for Reservations.
Where should the code be located that displays all reservations for a specific user?
Is this done in the User controller or the Reservation controller?

Upvotes: 1

Views: 93

Answers (3)

varatis
varatis

Reputation: 14740

It depends. If you're dealing with a nested resource (in other words you want to be able to access something like /users/4321/reservations), you should take a look at this Railscast, which is outdated for Rails 2 but still useful.

What you probably want is to have the code be in the ReservationsController under the index action, but it depends on what you're planning to do. Nonetheless, something like this would make sense:

class ReservationsController < ApplicationController
  def index
    @reservations = Reservations.where(user: params[:user_id])
  end
end

Upvotes: 2

Jiř&#237; Posp&#237;šil
Jiř&#237; Posp&#237;šil

Reputation: 14401

Where should the code be located that displays all reservations for a specific user?

It depends. If you want to show reservations for a specific user on his detail page (/users/42), then UsersController#show action is perfectly reasonable. If you want to make a search form, then it's basically a filter on the ReservationsControler#index action.

Upvotes: 0

ScottJShea
ScottJShea

Reputation: 7111

I think you are slightly off base here... your models should have an association; e.g.:

User < ActiveRecord::Base
 has_many :reservations
end

Your UserController#show might be

def show
 @user = User.find(params["id")
end

And then the view would have something like:

<ul>
    <% @user.reservations.each do |r| %>
    <li><%= r.details =%></li>
    <% end %>
</ul>

The association opens it up so that you can call the needed object from either. You could just as easily show @reservation.user.name in the Reservation view

Upvotes: 0

Related Questions