Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 667
Baub Avatar asked May 25 '12 19:05

Baub


3 Answers

Product.where(:id => params[:ids].split(','))
like image 76
Yuri Barbashov Avatar answered Oct 19 '22 03:10

Yuri Barbashov


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.

like image 22
Renra Avatar answered Oct 19 '22 01:10

Renra


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.

like image 42
Nick Colgan Avatar answered Oct 19 '22 02:10

Nick Colgan