我是 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
我不明白為什么。有人能幫我嗎?
uj5u.com熱心網友回復:
看起來您認為的validates ... if:作業方式與實際作業方式不同。這條線
validates :to_id, presence: true, if: :from_different_to?
to_id如果from_different_to方法回傳,則轉換為驗證是否存在true。當from_different_to評估為false然后不驗證。請參閱Rails 指南。
這意味著當你定義
@trip.to_id = @place1.id
assert_not @trip.valid?
在您的測驗中,第一行禁用檢查to_id. 沒有驗證,沒有錯誤...
我想,你真的努力實作是確認到to_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
uj5u.com熱心網友回復:
我不明白為什么。有人能幫我嗎?
這if有條件地啟用驗證。你to_id是一樣的from_id,所以to_id根本沒有經過驗證。但即使是,to_id也有值,所以這個欄位不會有錯誤。
總的來說,我不太確定您為什么會在這里出現驗證錯誤或該錯誤應該是什么。根據我的經驗,像這樣assert_not @model.valid?的斷言實際上毫無用處。由于無關的原因,該記錄可能無效,您將一無所知。就個人而言,我斷言我期望的確切錯誤訊息。沿著這些路線的東西(rspec 語法)
it "requires first_name" do
expected_messages = {
first_name: [:blank],
}
@model.valid?
expect(@model.errors.full_messages).to eq expected_messages
end
uj5u.com熱心網友回復:
@spickermann 的替代方案是:
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, numericality: {other_than: :from_id}, if: :from_place_id?
def from_place_id
from_id
end
def from_place_id?
!from_id.nil?
end
end
請注意,只有當 from_id 不為空時,我們才必須放置一個控制元件來執行最后一次驗證,因為如果我們不這樣做,我們將取消validates :from_id, presence:true上級行上的控制元件。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/328635.html
