Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to check and validate non model parameters in Rails

Where do you check URL parameters that are not model attributes (like page, per_page, sort_mode) in Ruby On Rails? In the controller or in the model?

For example, when doing a more complicated database query, would you check the params and maybe set defaults in the controller and then do for example MyModel.search(page, per_page, order, sort_mode, query), or would you setup the validation inside the model and just pass the non manipulated params MyModel.search(params)?

And how do you report that parameter back to the view? For example a sort_mode parameter that should result in a little arrow on the view for sort direction. Do you check and clean up the params hash and get the data in the view from params, or do you use an own instance variable for that?

like image 487
Zardoz Avatar asked Mar 17 '11 09:03

Zardoz


People also ask

How do I validate in Ruby on Rails?

This helper validates the attributes' values by testing whether they match a given regular expression, which is specified using the :with option. Alternatively, you can require that the specified attribute does not match the regular expression by using the :without option. The default error message is "is invalid".

What is the difference between validate and validates in rails?

validates is used for normal validations presence , length , and the like. validate is used for custom validation methods validate_name_starts_with_a , or whatever crazy method you come up with. These methods are clearly useful and help keep data clean. That test fails.

How does validate work in Rails?

Rails validation defines valid states for each of your Active Record model classes. They are used to ensure that only valid details are entered into your database. Rails make it easy to add validations to your model classes and allows you to create your own validation methods as well.


1 Answers

I tend to sanitise params in the controller.

class ApplicationController < ActionController::Base
  before_filter :sanitise_params

  protected

  def sanitise_params
    # tidy up
    # set defaults
  end
end

Good practice that the Models declare their interface and it's up to the Controllers to talk to them in the correct way. That way you have a clear separation of your layers.

View helpers are there to help with the views. Here are some examples that come as part of ActionPack's ActionView. You can put your own in app/helpers

like image 141
lebreeze Avatar answered Sep 19 '22 08:09

lebreeze