Rails 3 - 接受销毁前验证的嵌套属性
我有一个接受_nested_attributes_for klasses 的教师模型。如果 klass 中有用户并且我想打印验证消息,我不希望能够删除 klass。
这就是我所拥有的...
class Teacher < ActiveRecord::Base
accepts_nested_attributes_for :klasses, :reject_if => proc { |a| a['name'].blank? }, :allow_destroy => true
end
class Klass < ActiveRecord::Base
belongs_to :teacher
has_many :users
before_destroy :reject_if_has_users
private
def reject_if_has_users
if users.length > 0
errors.add_to_base "You cannot delete this class as it contains users."
false
else
true
end
end
end
当我尝试从包含用户的教师中删除 klass 时,当我使用 Accepts_nested_attributes_for 并传入“klasses_attributes”=>{“0”=>{”时,我希望验证失败name"=>"test", "_destroy"=>"1", "id"=>"17183"} 哈希。
如果我没有 error.add_to_base 行,上述方法将阻止 klass 被删除。但是,它不会导致显示验证消息。当我有那行时,它不会阻止删除。
谢谢,
蒂姆
I have a teachers model that accepts_nested_attributes_for klasses. I don't want to be able to delete the klass if there are users in the klass and I want to print a validation message.
This is what I have...
class Teacher < ActiveRecord::Base
accepts_nested_attributes_for :klasses, :reject_if => proc { |a| a['name'].blank? }, :allow_destroy => true
end
class Klass < ActiveRecord::Base
belongs_to :teacher
has_many :users
before_destroy :reject_if_has_users
private
def reject_if_has_users
if users.length > 0
errors.add_to_base "You cannot delete this class as it contains users."
false
else
true
end
end
end
I want the validation to fail when I try removing a klass from a teacher that contains users when I am using accepts_nested_attributes_for and passing in a "klasses_attributes"=>{"0"=>{"name"=>"test", "_destroy"=>"1", "id"=>"17183"} hash.
The above method will prevent the klass from being removed if I don't have the error.add_to_base line. It won't however cause a validation message to be shown. When I have that line, it doesn't prevent the deletion.
Thanks,
Tim
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
删除记录时不会进行验证,仅在保存记录时才会进行验证。我在一个项目中处理此问题的方法是在模型中引发异常,然后在控制器中挽救该异常并显示闪光警报。像这样:
型号:
教师控制器:
Validation doesn't take place when deleting a record, only when saving a record. The way I handled this in one of my projects is raising an exception in the model and then rescueing from that exception in my controller and showing a flash alert. Like this:
Model:
Teachers controller: