1

I've created my REST API based on Michael Scott from the Office, so far if you go onto the main part of the API it displays all the quotes /api/v1/quotes/ and you can get individual ones if you add an id number such as /api/v1/quotes/5,but I want users to be able to get a random quote when they put in a GET request.

This would preferably be done with an extra part of the URL such as /api/v1/quotes/random.

I've looked at a lot online but I can't figure this out. Do I put my code into the quotes controller and create another function or do I have to put this somewhere else such as routes.db? Also do I put in the SQL function of RANDOM or is there a better and more efficient way to randomise it. My database only has 50 records in it and it's done in mysql2.

Thanks in advance.

It's my first time posting here as usually I hate asking for help as I think I can always figure it out myself but I'm extremely new to Ruby so I'm fairly clueless on how to solve this. If you need me to clarify my question then just let me know.

2 Answers2

2

You can do that in Model as well as controller.

Model:

class Model < ApplicationRecord
  def self.random
   Model.limit(1).order("RANDOM()").first
  end
end

Controller: In method show

def show
   render json: Model.find_by(id: params[:id]) || Model.random
end

I hope that helpful.

Piyush Awasthi
  • 279
  • 2
  • 11
1

I would configure a quotes/random collection route:

# in config/routes.rb
resources :quote do
  get 'random', on: :collection
end

and use a controller method like this:

# in controllers/quotes_controller.rb
def random
  @quote = Quote.order('RAND()').first
  render :show
end

Please note: Returning a single random row from a table is database specific – for MySQL

ORDER BY RAND() LIMIT 1

seems to be the way to go.

spickermann
  • 81,597
  • 8
  • 83
  • 112