开发者

Is there a plugin/gem that lets you inherit errors from a child model in rails?

开发者 https://www.devze.com 2023-02-14 04:22 出处:网络
Let\'s assume you are using Rails, and have a form with nested models; for example, a form with Project and Tasks for the project.

Let's assume you are using Rails, and have a form with nested models; for example, a form with Project and Tasks for the project.

Then assume that each tas开发者_如何学运维k must have a name, however a user does not enter a name. When the user submits the form, and you use

project.update_attributes(params[:project]) 
=> raises error

But (as seen above) this raises an error. Are there any tools out there that will allow the errors from the task to percolate up to the project level, and NOT raise an error? Such a tool would greatly reduce duplication, and it would have to prevent both the project AND OTHER sub-tasks from being saved in the same call to 'update_attributes'.

On a side note, the problem I am trying to solve is the problem of not having to rewrite that percolation code for about 30 models,


Validation errors from associations should be available in the parent's #errors method. Example, if "Foo" has one "Bar":

ruby-1.9.2-p136 :001 > s = Foo.new
 => #<Foo id: nil, created_at: nil, updated_at: nil, enabled: true, alpha: nil> 
ruby-1.9.2-p136 :002 > s.build_bar
 => #<Bar id: nil, created_at: nil, updated_at: nil, foo_id: nil, beta: nil> 
ruby-1.9.2-p136 :003 > s.save
 => false 
ruby-1.9.2-p136 :004 > s.errors.full_messages
 => ["Alpha is invalid", "Bar beta can't be blank"] 
ruby-1.9.2-p136 :005 > 

Furthermore, I don't think your models should be raising exceptions if there is a validation failure (if this is what you mean by "raise error"). You should just see #update_attributes return false, and then you can fetch the error list

0

精彩评论

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

关注公众号