在Rails中检查和验证非模型参数的位置 [英] Where to check and validate non model parameters in Rails

查看:69
本文介绍了在Rails中检查和验证非模型参数的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您在哪里检查不是Ruby On Rails中模型属性的URL参数(例如page,per_page,sort_mode)?在控制器中还是在模型中?

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?

例如,当执行更复杂的数据库查询时,您将检查参数并在控制器中设置默认值,然后执行例如MyModel.search(page, per_page, order, sort_mode, query),还是在模型内部设置验证并仅通过非操作参数MyModel.search(params)?

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)?

您如何将该参数报告回视图?例如,sort_mode参数应导致视图上的小箭头指示排序方向.您是检查并清理params哈希并从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?

推荐答案

我倾向于清理控制器中的参数.

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.

视图帮助器可以帮助您查看视图.这是一些示例,它们是ActionPack的ActionView的一部分.您可以将自己的内容放入app/helpers

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

这篇关于在Rails中检查和验证非模型参数的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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