Search code examples
ruby-on-railsrestcrudapi-designweb-development-server

Handle non-REST logic in Rails API


For example, let's say I have a Post resource. With GET /posts I retrieve all posts (index action). What if I want to retrieve trending posts (posts with a lot of likes in the last 24 hours)? Should I implement the logic in the index action (through a parameter), or should I implement a new action trending that responds to a new endpoint GET /trending, making the API non-REST?

Note: I read this article and I understand the parameter way, but I can't figure out how adding an extra endpoint works...


Solution

  • you can do both. I would opt for the new action. But you can pass an extra param as well in a link:

    link_to posts_path(trending: true)

    In your controller you can then check if params[:trending].present? and then only pass to the posts variable @posts the trending posts.

    You can also assign the trending indicator to a variable that will be passed to the index view so that you can adapt the layout (change header from "posts" to "trending posts") with if params[:trending].present? then @trending = true end

    Creating a new action makes controllers and views less cluttered with conditions (if ...)

    By the way, creating a new action is still a REST logic if you make it a GET query. If your new action was about updating a post it would need be a PATCHquery