John
John

Reputation: 135

Ruby on Rails Sometimes Nested Resource

In a Ruby on Rails app I'm working on (2.3.8), I have a model User that can have Workouts

class Workout < ActiveRecord::Base
    belongs_to :user
end

I also have Trainer->Client relationships (all tied to the User model through a join table) A user can add workouts for himself, BUT a trainer can also add workouts for his clients.

I've set up the routes as follows:

map.resources :workouts
map.resources :clients, :has_many => 'workouts'

Both sets of routes are working (ie. /workouts and /clients/1/workouts). I've updated the workouts_controller so that depending on if there is a client_id I will show a different set of workouts

def index
    if(params[:client_id])
        @workouts = Workout.find_all_by_user_id(params[:client_id])
    else
        @workouts = Workout.find_all_by_user_id(@current_user.id)
end

My question is, how do I set up my views to work correctly. Depending on how I got to index I want to link differently to the add or edit screen. Should I just do everything conditionally...

<% if (@client.nil?) %>
    <%= link_to 'New workout', new_workout_path %>
<% else %>
    <%= link_to 'New workout', new_client_workout_path(@client) %>
<% end %>

...or is there some easier way to split these two cases out? It seems like I'll have a lot of conditions in the views and controllers and didn't know if this is the way to handle this case or not.

Upvotes: 0

Views: 128

Answers (1)

bjg
bjg

Reputation: 7477

This looks like a good candidate for creating a link_to wrapping helper in WorkoutHelpers into which you can pass the @client instance. If it's nil you emit one link type otherwise emit the other. Then you can get rid of all those conditionals in the view and make it more legible.

To be even more general and DRY, you could pass in more info into he helper to help use the right path helper such as new_workout_path or edit_workout_path, etc

Same suggestion would apply to the general case where you have a lot of similar conditional branching in views.

Upvotes: 1

Related Questions