2

I am using rails 4.2 of my application.

Below is index action of my Descriptions Controller.

def index
  @descriptions = Description.all
  if name = params[:name]
    description = @descriptions.where(name: name)
    render json: description
  end
end

and when I input http://localhost:3000/descriptions?name=LA to browser. I can get a data which name attributes is "LA" in JSON format. like below.

[{"id":140,"name":"LA","value":"Lakers","api_name_id":113,"created_at":"2015-06-04T17:11:18.649Z","updated_at":"2015-06-04T17:11:18.649Z"}]

However, if I pass two parameter at the end of my url like

http://localhost:3000/descriptions?name=LA&name=123

I can only get data which name attributes is "123" in JSON format.

[{"id":143,"name":"123","value":"456","api_name_id":114,"created_at":"2015-06-04T17:20:18.703Z","updated_at":"2015-06-04T17:20:18.703Z"}]

Is there any way that I can get all datas which name attributes is "LA" and also "123" ? Like below

[{"id":143,"name":"123","value":"456","api_name_id":114,"created_at":"2015-06-04T17:20:18.703Z","updated_at":"2015-06-04T17:20:18.703Z"},{"id":140,"name":"LA","value":"Lakers","api_name_id":113,"created_at":"2015-06-04T17:11:18.649Z","updated_at":"2015-06-04T17:11:18.649Z"}]
Dreams
  • 8,288
  • 10
  • 45
  • 71

2 Answers2

1

Hit the url as :

http://localhost:3000/descriptions?name[]=LA&name[]=123

And rest your code is perfect. But remember where will do SQL IN operation. Look this answer to see how to pass array like elements with query string.

Community
  • 1
  • 1
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
0

maybe you'll want

unless params.empty?
 description = {}
 params.each do |key, value|
  description.merge(@descriptions.where(name: value)) if key == name
 end
end
rkamun1
  • 338
  • 1
  • 2
  • 15