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

人盡茶涼 提交于 2019-12-12 15:01:58

问题


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?


回答1:


In most cases, you should not have to validate request parameters in your controller.

The best practice for model form validations (required, unique, length, max, etc. ) is to define validations in the model i.e. /models/group.rb, and use a form library such as simple_form which automatically handles the model validations you've defined.

For example, in your group.rb you'll have:

class Group < ActiveRecord::Base
  validates :group, presence: true
end

If you absolutely need to validate in your controller, use Action Controller Filters: http://guides.rubyonrails.org/action_controller_overview.html#filters

References:

http://guides.rubyonrails.org/active_record_validations.html https://github.com/plataformatec/simple_form




回答2:


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



来源:https://stackoverflow.com/questions/28921623/how-to-validate-request-parameters-in-rails-4-like-laravel-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!