如何编写验证来确保现有关联在 Rails 3 中无法更改?
我见过很多问题询问如何验证关联的存在,但这个问题有点复杂。
假设我有三个模型:一个 Plane
、一个 Pilot
和一个 Flight
。
一架飞机
可以配备一名飞行员
和一名航班
。
一旦为飞机
分配了飞行员
,就可以为其分配航班
。
我想编写一些验证代码,以确保一旦Plane
同时拥有Flight
和Pilot
,Pilot
无法更改。 因此,我希望此测试能够通过:
describe Plane do
context "before updating" do
it "ensures that the pilot cannot be changed if the plane has any flights" do
plane = Plane.create!
plane.pilot = Pilot.create!
plane.flight = Flight.create!
hijacker = Pilot.create!
plane.pilot = hijacker
plane.save.should be_false
plane.errors[:base].should include "Can't change the pilot while in-flight"
end
end
end
我希望了解可以使用哪些技术来实现此目的。谢谢大家!
I have seen many questions asking how to validate the presence of an association, but this question is a bit more complex.
Say I have three models, a Plane
, a Pilot
, and a Flight
.
A Plane
can have one Pilot
and one Flight
.
Once a Plane
has been assigned a Pilot
, it can then be assigned a Flight
.
I would like to write some validation code to ensure that once a Plane
has both a Flight
and a Pilot
, the Pilot
cannot be changed. So I would like this test to pass:
describe Plane do
context "before updating" do
it "ensures that the pilot cannot be changed if the plane has any flights" do
plane = Plane.create!
plane.pilot = Pilot.create!
plane.flight = Flight.create!
hijacker = Pilot.create!
plane.pilot = hijacker
plane.save.should be_false
plane.errors[:base].should include "Can't change the pilot while in-flight"
end
end
end
I would love some insight as to what techniques are available to accomplish this. Thanks all!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以从自定义验证开始,根据数据库中实际的基础记录检查更改的记录(位于内存中)。
You could start with a custom validation that checks the changed record (sitting in memory) against the underlying record that's actually in the database.
您可以编写自己的验证来确保这一点..
但在你指派飞行员的那一刻,但在最后,当你拯救飞机时,这不会返回错误。
所以这里是更简单的版本:
希望这会有所帮助(或至少为您导航正确的方向)。
问候,诺斯
you can write your own validation to ensure this..
but that wouldn't return false to you in the moment you assign a pilot, but at the end, when you save the plane.
So here is simpler version:
Hope this helps (or at least navigate you the right direction).
Regards, NoICE