standup75
standup75

Reputation: 4814

Simplify/RESTify my routes!

Here is a sample of my routes.rb Basically I have users that have pictures and that can rate other people's pictures

This is not very RESTful at all, but I cannot figure out how to turn this around?

  resources :users do
    member do
      post :reset_password
    end
  end
  # to list images
  get 'images/list/:order/:page/:per_page/:category', :to => 'images#list_filtered'
  # to rate images
  post 'images/rate', :to => 'images#rate'
  # to list a user's images
  get 'images/user/:user_id/:category/:order/:page/:per_page', :to => "images#user"
  # to list users that rated an image
  get 'users/rated/:image_id', :to => 'users#rated'

Upvotes: 0

Views: 327

Answers (2)

edgerunner
edgerunner

Reputation: 14983

Why don't you treat images and ratings as resources? Nest images under their users and add a Rating model that belongs to an image and a user (the user giving the rating, not the owner of the rated image)

resources :users do
  resources :images do
    resources :ratings, :only => [:create, :destroy]
  end
  post :reset_password, :on => :member
end

then you can set up your cotroller like this

# ratings_controller.rb
class RatingsController < ApplicationController
  before_filter :find_image

  # POST /users/26/images/351/ratings
  def create
    @image.ratings.create(params[:rating])
    redirect_to image_path(@image), :notice => "You just rated this image"
  end

  # DELETE /users/26/images/351/ratings/35477
  def destroy
    @image.ratings.find(params[:id]).destroy!
    redirect_to image_path(@image), :notice => "Deleted rating"
  end

  private

  def find_image
    @image = Image.where(:user_id => params[:user_id], :id => params[:image_id])
  end
end

Upvotes: 1

Pan Thomakos
Pan Thomakos

Reputation: 34350

Here are a couple of things I would recommend:

  1. Use images#index instead of images#list_filtered and pass order, page, per_page and category as parameter: /images?order=...&per_page=...&page=...
  2. Make images nested under users as resources and then make images a top level resource that is independent of user (so that you can view all images or you can view user specific images).
resources :users do
  member do
    post :reset_password
  end
  resources :images
end

resources :images do
  post :rate
  get :rated
end

You should then be able to view images using /images.

You should be able to rate an individual image using /images/:id/rate.

You should be able to view users who rated an image using /images/:id/rated.

You should be able to list a user's images using /user/:id/images.

Upvotes: 0

Related Questions