gpt4 book ai didi

ruby-on-rails - belongs_to关联在实例化时发生冲突, "Validation failed... must exist"错误

转载 作者:行者123 更新时间:2023-12-04 03:50:38 29 4
gpt4 key购买 nike

这就是我进行关联的方式:

class Event < ApplicationRecord
has_one :lineup
has_many :artists, :through => :lineup
belongs_to :venue
end

class Lineup < ApplicationRecord
belongs_to :artist
belongs_to :event
end

这就是我尝试播种的方式

Event.create!(name: "The Function", 
date: DateTime.new(2016,2,3,10,0,0,'+7'),
venue: Venue.create!(name: "Speakeasy", address: "Lynwood Ave", zip_code: "30312"),
lineup: Lineup.create!(:artist => Artist.create!(name: "DJ Sliink", bio: "jersey club king")),
description: "free free free")

我得到的错误是 ActiveRecord::RecordInvalid: Validation failed: Event must exist 指向 lineup 行。如果我设置 lineup: nil,我会收到相同的消息,然后在创建 Event 后,尝试执行 event1.lineup = Lineup.create!... 。我有什么选择可以摆脱 Lineup 对现有事件的依赖?据我了解,问题出在 belongs_to 关系上,因为如果我从 Lineup 实例创建中取出 artist: ,我也会得到 Artist must存在错误。

验证:

> Event.validators
=> [#<ActiveRecord::Validations::PresenceValidator:0x007fcaab69fa78 @attributes=[:venue], @options={:message=>:required}>]

> Lineup.validators
=> [#<ActiveRecord::Validations::PresenceValidator:0x007fcaad988238 @attributes=[:artist], @options={:message=>:required}>, #<ActiveRecord::Validations::PresenceValidator:0x007fcaab77c7c0 @attributes=[:event], @options={:message=>:required}>]

如果种子文件中没有 !,我会得到一个完全不同的错误 - ActiveRecord::AssociationTypeMismatch: Venue(#70094220768860) expected, got Fixnum(#70094214808600) ,虽然仍然是 event = Event.create 行。

最佳答案

在 Rails 5 中 belong_to 默认充当 validates_presence_of 所以为了允许一个不存在的关系添加 optional: true 选项到属于_to。例如:

belongs_to :parent,
optional: true

关于ruby-on-rails - belongs_to关联在实例化时发生冲突, "Validation failed... must exist"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36025210/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com