我有一个简单的API示例和简单的GET路由。我有MongoDB,我的集合文档看起来像这样:
{
"_id" : ObjectId("51411cf11b4cb1b19a7115c0"),
"name" : "some_name",
"type" : "some_type",
"services" : [
"service_one",
"service_two"
],
"location" : {
"type" : "some_type",
"description" : "Some description",
},
"address" : {
"street" : "some_street",
"building" : "building",
"post_code" : "some_post_code",
"city" : "some_city",
"province" : "some_province"
}
}
我的控制器:
class V1::DataController < V1::ApplicationController
def index
@data = Data.all
render 'v1/data/index'
end
def show
@data = Data.find_by(name: params[:id])
render json: @data
end
end
我使用 jbuilder 来渲染我的输出。现在,我的问题是,如何使该参数在 url 中传递,反映在 json 结果中?例如,我的 Mongo 文档有"名称",所以我想按名称对结果进行排序。
http://api.loc:3000/data?name=some_name
你能写一个简单的例子吗?
谢谢。
示例中使用的一些命名约定有点奇怪。如果您只想排序,我会考虑将"name"参数更改为更具描述性的参数。与您的示例保持一致,以下内容可能会有所帮助。
class V1::DataController < V1::ApplicationController
...
def index
#ASC
if data_params[:order].eql?('asc')
@data = Data.asc(data_params[:name])
else
#DESC
@data = Data.desc(data_params[:name])
end
render 'v1/data/index'
end
def data_params
params.permit(:name, :order)
end
end