我正在使用应用程序的rails 4.2。
以下是我的描述控制器的索引操作。
def index
@descriptions = Description.all
if name = params[:name]
description = @descriptions.where(name: name)
render json: description
end
end
当我向浏览器输入http://localhost:3000/descriptions?name=LA时。 我可以获得一个名称属性为JSON格式的“LA”的数据。 如下。
[{"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"}]
但是,如果我在我的网址末尾传递两个参数,如
http://localhost:3000/descriptions?name=LA&name=123
我只能以JSON格式获取名称属性为“123”的数据。
[{"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"}]
有什么方法可以获得名称属性为“LA”和“123”的所有数据?如下所示
[{"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"}]
答案 0 :(得分:1)
点击网址:
http://localhost:3000/descriptions?name[]=LA&name[]=123
休息你的代码是完美的。但请记住where
将执行SQL IN
操作。查看此answer以了解如何使用查询字符串传递数组元素。
答案 1 :(得分:0)
也许你想要
unless params.empty?
description = {}
params.each do |key, value|
description.merge(@descriptions.where(name: value)) if key == name
end
end