开发者

Rails: Is it improper to freak out during validation (with exceptions)?

You have a Lung model. In it, you put:

validates_presence_of :human_id

Users of your app have no control over whether or not human_id is set; the application should be doing it automatically.

If :human_id were ever not present, it doesn't help your users to tell them "this lung isn't attached to a human", because your users won't be able to do anything about it. Is it time for your model to freak out and throw an exception?

Should your models ever care about the severity of a given validation error? Is that part of business logic? Should models ever throw exceptions during validation, or should the controllers be responsible to interpreting the "dumb" validation from the开发者_StackOverflow中文版 model and generating useful data for the view?

Edit: If this is an acceptable thing to do, are there any conventions regarding how to throw exceptions during a model's validation?


I would set up my ActiveRecord migration so that the human_id column cannot be null. That way you'd get an exception anyway if it's not set.

create_table :lungs do |t|
  t.integer :human_id, :null => false
  ...
end


I think it should be raised as a exception. The Application would be putting the human_id in most of the cases and only in exceptional cases the human_id might not be present, like say an crafted request or timed logout in the backend. Since these are exceptional cases it's worthwhile to throw exceptions instead of letting the controller handle it.


In my understanding validations are not the right place to check this kind of model consistency. Validations are only for user generated input.

The question is: how would it be possible that a Lung is created without a human id? If the answer is only through a programming order, you should propably fix that bug and create some test cases for it. Or if you really want to check it every time, you could check it inside a before_save callback.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜