ruby-on-rails - Rails 条件验证:如果:不起作用
问题描述
我是 Rails 新手,我有一个带有三个外键的旅行课程。其中两个将其与同一类相关联:Place。
这是我的模型:
class Trip < ApplicationRecord
belongs_to :from, class_name: "Place", foreign_key: "from_id"
belongs_to :to, class_name: "Place", foreign_key: "to_id"
belongs_to :vehicle, class_name: "Vehicle", foreign_key: "vehicle_id"
validates :price, presence: true
validates :time, presence: true
validates :from_id, presence: true
validates :to_id, presence: true, if: :from_different_to?
def from_different_to?
to_id != from_id
end
end
除最后一项外,所有模型测试均通过:
class TripTest < ActiveSupport::TestCase
def setup
@place1 = Place.create(name:"NewYork",cap:"11111",lat:"1234",long:"1478")
@place2 = Place.create(name:"Los Angeles", cap:"22222", lat:"1234",long:"1478")
@vehicle = Vehicle.create(targa: "ab123cd",modello:"500",marca:"Fiat", posti:5,alimentazione:"benzina")
@trip = Trip.new(price: 10, time: Time.new(2021, 10, 14, 12,03), from_id: @place1.id, to_id: @place2.id,vehicle_id: @vehicle.id)
end
...
test "Departure id and arrival id should be different" do
@trip.to_id = @place1.id
assert_not @trip.valid?
end
导致失败:
Failure:
TripTest#test_Departure_id_and_arrival_id_should_be_different [/media/alessandro/DATA/Universita/Magistrale/1_anno/Programmazione_concorrente/hitchhiker/test/models/trip_test.rb:45]:
Expected true to be nil or false
我不明白为什么。有人能帮我吗?
解决方案
似乎您认为validates ... if:
的工作方式与实际情况不同。这条线
validates :to_id, presence: true, if: :from_different_to?
如果方法返回,则转换为验证to_id
是否存在。当评估为然后不验证。请参阅Rails 指南。from_different_to
true
from_different_to
false
这意味着当你定义
@trip.to_id = @place1.id
assert_not @trip.valid?
在您的测试中,第一行禁用检查是否存在to_id
. 没有验证,没有错误...
我想你真正想要实现的是验证 toto_id
存在并且 from_id
不to_id
相等。这可以通过这样的自定义验证来完成:
validates :to_id, presence: true
validate :validates_places_are_different
private
def validates_places_are_different
errors.add(:to_id, "must be different to from_id") if to_id == from_id
end
推荐阅读
- python - 在 Python 中创建条件
- clojure - 合并同一集合的功能
- ios - 如何仅在 Apple Watch 应用程序中打开网页链接?
- linq - 为子属性创建 MethodCallExpression
- django - 自定义用户模型的 Wagtail 迁移错误
- android - 无法更改 MutableList 中的对象属性
- woocommerce - 自定义产品类型在更新时不更改类型
- android - 在 Android 10 中以更“通用”的方式断开与 Wi-Fi 网络的连接
- laravel - 使用 Laravel 在嵌套路由中调用 2 次 VueJS 组件
- java - 为什么“addOnSuccessListener”的代码在以下代码块中的执行过程中会被跳过?