验证 Restful 个端点中的参数
Validate paramaters in Restful endpoints
我是 rails restful 网络服务的新手,我正在尝试构建 returns json 转储 deals.So 的服务 deals.So returns 当您点击 http://localhost:3000/api/deals 时,这些交易以 json 格式显示。现在我想在 uri http://localhost:3000/api/deals?deal_id=2&title=book
中添加两个强制参数(deal_id 和标题)和两个可选参数。验证这两个强制参数的最佳方法是什么?换句话说,我只想在 deal_id 和 title 参数存在时才进行查询。假设交易模型有字段 deal_id、标题、描述和供应商。
这是我的代码
控制器
module Api
class DealsController < ApplicationController
respond_to :json
def index
@deals = Deal.all
respond_with (@deals)
end
end
end
路线
namespace :api,:defaults => {format:'json'} do
resources :deals
end
要验证 Rails 路由中是否存在查询参数,您可以使用 :constraints
选项。所以,在你的情况下,如果你想要求存在参数 deal_id
和 title
,你可以通过更改来实现:
resources :deals
收件人:
resources :deals, :constraints => lambda{ |req| !req.params[:deal_id].blank? && !req.params[:title].blank? }
然后,在您的控制器中,您可以访问 params
散列中的所有四个参数。
或者,如果您想提供对用户更友好的错误消息,您可以在控制器中进行验证。有许多方法。我可能会这样做:
def action
if params[:deal_id].blank? || params[:title].blank?
flash[:warning] = 'Deal ID and title must be present'
redirect_to root_path and return
end
#rest of your code goes here
end
我是 rails restful 网络服务的新手,我正在尝试构建 returns json 转储 deals.So 的服务 deals.So returns 当您点击 http://localhost:3000/api/deals 时,这些交易以 json 格式显示。现在我想在 uri http://localhost:3000/api/deals?deal_id=2&title=book
中添加两个强制参数(deal_id 和标题)和两个可选参数。验证这两个强制参数的最佳方法是什么?换句话说,我只想在 deal_id 和 title 参数存在时才进行查询。假设交易模型有字段 deal_id、标题、描述和供应商。
这是我的代码
控制器
module Api
class DealsController < ApplicationController
respond_to :json
def index
@deals = Deal.all
respond_with (@deals)
end
end
end
路线
namespace :api,:defaults => {format:'json'} do
resources :deals
end
要验证 Rails 路由中是否存在查询参数,您可以使用 :constraints
选项。所以,在你的情况下,如果你想要求存在参数 deal_id
和 title
,你可以通过更改来实现:
resources :deals
收件人:
resources :deals, :constraints => lambda{ |req| !req.params[:deal_id].blank? && !req.params[:title].blank? }
然后,在您的控制器中,您可以访问 params
散列中的所有四个参数。
或者,如果您想提供对用户更友好的错误消息,您可以在控制器中进行验证。有许多方法。我可能会这样做:
def action
if params[:deal_id].blank? || params[:title].blank?
flash[:warning] = 'Deal ID and title must be present'
redirect_to root_path and return
end
#rest of your code goes here
end