首页 > 解决方案 > 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

我不明白为什么。有人能帮我吗?

标签: ruby-on-railsrubytesting

解决方案


似乎您认为validates ... if:的工作方式与实际情况不同。这条线

validates :to_id, presence: true, if: :from_different_to?

如果方法返回,则转换为验证to_id是否存在。当评估为然后不验证。请参阅Rails 指南from_different_totruefrom_different_tofalse

这意味着当你定义

@trip.to_id = @place1.id
assert_not @trip.valid?

在您的测试中,第一行禁用检查是否存在to_id. 没有验证,没有错误...

我想你真正想要实现的是验证 toto_id存在并且 from_idto_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

推荐阅读