swaroopsm
swaroopsm

Reputation: 1399

Rails best practice for creating a resource on a relational model

I would like to know what would be the best way to create / destroy a relational resource. For Eg.: I have two models called Picture and Favorite. A user can add a picture to his favorites.

class Picture 

end


class Favorite

 belongs_to :picture
 belongs_to :user

end

I would like to know which is the best place(practice) to add login in order to add a picture to his / her favorites. Is it better to add it in the PicturesController with a favorite action that would create or delete the favorite based on its existence, or else create a separate controller called FavoritesController and add two actions called create and destroy?

Upvotes: 0

Views: 65

Answers (1)

Guilherme Franco
Guilherme Franco

Reputation: 1483

The best approach following both Rails conventions and RESTful principles would be to create a controller per resource, containing the actions necessary to manipulate that resource. Based on your situation, you have a Favorite resource that can be both created and destroyed, so the route mapping should be something like this:

  Prefix Verb   URI      Pattern                  Controller#Action
  favorites     POST     /favorites(.:format)     favorites#create
  favorite      DELETE   /favorites/:id(.:format) favorites#destroy

And your controller should look like this:

class FavoritesController < ApplicationController
  def create
    # Create a favorite here based on its params !
  end

  def destroy
    # Destroy a favorite here based on its id !
  end
end

About the login process, I really think it should be a concern of your UsersController, though some Ruby devs prefer to use SessionsController, since it is a Devise default.

Notice that you have the option to create nested resource routes which is a good idea when mapping has_one / belongs_to relations into routes, and it is indeed a best practice. You can check Rails Guides for details.

I'm not suggesting this kind of approach here, because when it comes to the User resource, it is not a good idea to have its id on your routes, and it is kind of a default to work with it in the backend.

I hope it helps :P

Upvotes: 1

Related Questions