关于自定义验证方法的建议
我正在使用 Ruby on Rails 3,我想知道我验证新记录的方法是否良好。
我不使用常见的 RoR 验证系统,因此在我的模型中,我拥有如下所有自定义验证方法:
def validates_user_name(user)
...
end
def validates_user_surname(user)
...
end
...
我以这种方式从控制器调用
def create
...
@user.validates_user_name(params[:user])
@user.validates_user_name(params[:user])
...
end
这是验证新创建的好方法吗用户?黑客使用这种方式会有问题吗?
I am using Ruby on Rails 3 and I would like to know if my approach to validate new record is good or not.
I don't use the common RoR validation system, so in my model I have all custom validation mathods like these:
def validates_user_name(user)
...
end
def validates_user_surname(user)
...
end
...
that I call from controller in this way
def create
...
@user.validates_user_name(params[:user])
@user.validates_user_name(params[:user])
...
end
Is it a good way to validate the creation of new user? There will be problems with hackers using this approach?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为您将很难让任何人相信您的自定义验证比 Rails 中内置的验证更好,尤其是在验证逻辑相似的情况下。
如果您仍然想控制事情发生的时间,您应该利用内置的回调挂钩,例如 创建之前。这样做有很多优点,包括自动事务回滚和解耦。但是,如果您正在做的事情已经由 Rails 完成,那么不建议重新发明轮子。
I think you're going to have a hard time convincing anyone that your custom validations are better than what's built into Rails, especially if the validation logic is similar.
If you still want control over when things happen, you should take advantage of the built-in callback hooks like before_create. There are lots of advantages of doing it this way, including automatic transaction rollback and decoupling. However, if what you're doing is already accomplished by Rails, it's not advisable to reinvent the wheel.