Baub
Baub

Reputation: 5044

Rails Get Multiple by ID

In Rails, I have a Product model. Sometimes I need to get multiple products at the same time (but the list is completely dynamic, so it can't be done on the Rails side).

So, let's say for this call I need to get products 1, 3, 9, 24 in one call. Is this possible? If so, do I need a custom route for this and what do I put in my controller?

i.e. does something like this work? /products/1,3,9,24

Upvotes: 11

Views: 11274

Answers (3)

Yuri  Barbashov
Yuri Barbashov

Reputation: 5437

Product.where(:id => params[:ids].split(','))

Upvotes: 4

Renra
Renra

Reputation: 5649

I would consider this a request to index with a limited scope, kind of like a search, so I would do:

class ProductsController < ApplicationController
  def index
    @products = params[:product_ids] ? Product.find(params[:product_ids]) : Product.all
  end
end

and then link to this with a url array:

<%= link_to 'Products', products_path(:product_ids => [1, 2, 3]) %>

this creates the standard non-indexed url array that looks kind of like

product_ids[]=1&product_ids[]=2 ...

Hope that helps.

Upvotes: 9

Nick Colgan
Nick Colgan

Reputation: 5508

I don't think you should need to change the routes at all. You should just have to parse them in your controller/model.

def show
  @products = Product.find params[:id].split(',')
end

If you then send a request to http://localhost/products/1,3,9,24, @products should return 4 records.

Upvotes: 28

Related Questions