Guilherme Oderdenge
Guilherme Oderdenge

Reputation: 5001

Method that checks for all results in the ActiveRecord

I'm creating an API to work with some slides and that's my routing:

  scope "/api/v1" do
    scope "/slides" do
      post "/" => "slides#create"
      get ":slide_id" => "slides#show"
      put ":slide_id" => "slides#update"
    end
  end

As you can see, there's just one get that expects the :slide_id parameter but and what if I want to display all results from that table? What should I do?

What I thought about

  scope "/api/v1" do
    scope "/slides" do
      post "/" => "slides#create"
      get "/" => "slides#show_all" # here's the magic
      get ":slide_id" => "slides#show"
      put ":slide_id" => "slides#update"
    end
  end

Did you saw the "magic"? Anyway, I'm feeling that's not the best way to do what I want, but I don't see any alternative, just to check if the method show has some parameter, if so, then display just what the user wants, otherwise, displays everything.

Can you give me some ideas?

Upvotes: 1

Views: 22

Answers (2)

Chen
Chen

Reputation: 584

I am not sure if I understand your requirement well.

You can make routing as bellow.

scope "/api/v1" do
    scope "/slides" do
      post "/" => "slides#create"
      get "(:slide_id)" => "slides#show" # slide_id param is optional
      put ":slide_id" => "slides#update"
   end
end

And in show action, check whether slide_id parameter is passed or not.

Upvotes: 1

marvelousNinja
marvelousNinja

Reputation: 1510

You should call that action index. And yes, it's perfectly valid solution to have a separate action to display collection of records. The variant with additional parameter smells a bit... If you're in doubt, you can always have a look at some examples. Twitter REST API for instance.

Upvotes: 1

Related Questions