如何在Laravel 5等Rails 4中验证请求参数? [英] How to validate request parameters in rails 4 like laravel 5?

查看:84
本文介绍了如何在Laravel 5等Rails 4中验证请求参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个动作控制器来验证来自视图的参数.

I have an action controller to validate params that are coming from view.


  def duplicate
    #params to be validated
    params = params[:group_to_duplicate]

    #params have to be validated to avoid method 'find' for some reason
    group = Group.find(params[:id])

    #validate to avoid this 'if'
    if group
      group.duplicate params
      notice = 'Some message'
    else
      notice = 'Some other message'
    end
    redirect_to groups_path, notice: notice

  end

如何验证来自视图的请求参数,例如laravel 5 输入链接说明在这里?

How to validate the request parameters coming from view, like laravel 5 enter link description here?

推荐答案

有时您确实需要验证请求参数,而不是模型.

Sometimes you do need to validate request params, and not the model.

API.您通常需要验证给定的参数.也许您需要一个返回股票行情的API的日期范围.

API's for example. You often need to validate the params given. Maybe you require a date range for an API that returns stock quotes.

报价模型是有效的,但是为了正确获取报价模型,您需要知道用户所需的范围,因为您不允许他们拥有完整的报价历史记录.这样的事情.

The quote model is valid, but in order to fetch it properly you need to know the range the user needs because you don't allow them to have the entire quote history. Something like that.

对于搜索表单也是如此.也许您有一个表单,要求用户在搜索雇员之前输入姓氏.

Also in the case of a search form. Maybe you have a form that requires the user to type the last name before searching for an employee.

在这些情况下,您可以使用表单或视图对象来帮助进行验证. 这是有关表单对象的快速文章: https://robots.thoughtbot.com/activemodel-form-objects

In these cases you can use form or view objects to help with the validation. Here's quick article on form objects: https://robots.thoughtbot.com/activemodel-form-objects

我也一直在看这个.我将在有空的时候试一试: https://github.com/nicolasblanco/rails_param

I've been looking at this as well. I'm going to give this a shot when I get some free time: https://github.com/nicolasblanco/rails_param

这篇关于如何在Laravel 5等Rails 4中验证请求参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆