Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate request parameters in rails 4 like laravel 5?

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

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

like image 588
Marcos Felipe Avatar asked Nov 23 '22 00:11

Marcos Felipe


1 Answers

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

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.

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

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

like image 122
jacklin Avatar answered Jan 23 '23 09:01

jacklin