Ruby on rails Rails构建属于“联合体”;必须存在”;错误
我正在尝试在rails中的“属于”模型关联中构建一个has\u many模型。关联是正确的,但它显示错误“必须存在”。我试着把可选的:真,但它似乎不工作 模型Ruby on rails Rails构建属于“联合体”;必须存在”;错误,ruby-on-rails,ruby,ruby-on-rails-5,Ruby On Rails,Ruby,Ruby On Rails 5,我正在尝试在rails中的“属于”模型关联中构建一个has\u many模型。关联是正确的,但它显示错误“必须存在”。我试着把可选的:真,但它似乎不工作 模型 class User::Product < ApplicationRecord has_one: :promo_code end class User::PromoCode < ApplicationRecord belongs_to: :product, optional: true accepts_neste
class User::Product < ApplicationRecord
has_one: :promo_code
end
class User::PromoCode < ApplicationRecord
belongs_to: :product, optional: true
accepts_nested_attributes_for :product
end
形式
当表单保存时,会出现一个错误,上面写着“必须存在”,我假设这是指\u中的外键
你知道我会做错什么吗?我认为上面的代码是关于这个问题的唯一相关代码。查看@engineersmnky链接的问题,当使用
接受嵌套的属性时,这似乎是一个已知的错误
这可以通过使用
的逆_选项来澄清双向关系来解决:
class User::Product < ApplicationRecord
has_one: :promo_code, inverse_of: :product
end
class User::PromoCode < ApplicationRecord
belongs_to: :product, optional: true, inverse_of: :promo_code
accepts_nested_attributes_for :product
end
class用户::产品
尝试一下,看看它是否能解决您的问题。分别在模型中尝试
has_one :promo_code, -> { PromoCode.order(:id) }, class_name: 'PromoCode',inverse_of: :product
belongs_to :product, inverse_of: :promo_code
您是否有顶级
产品
以及用户::产品
?@engineerinersnky没有用户只是名称空间。请看,这似乎是一个已知的问题,尽管可选:true
本应解决此问题谢谢您的回答,不幸的是,这没有解决此问题。啊,不好意思,谢谢你让我知道-给@chrisgeeq的答案一个机会,这似乎是该线程中的另一个建议,它帮助了相反的没有。这是一个严重的错误,希望你能尽快解决!出于某种原因,它以前从未抱怨过,但问题在代码的另一部分。改变了这一点,这个关系无论是否与之相反。谢谢你的帮助!
class User::Product < ApplicationRecord
has_one: :promo_code, inverse_of: :product
end
class User::PromoCode < ApplicationRecord
belongs_to: :product, optional: true, inverse_of: :promo_code
accepts_nested_attributes_for :product
end
has_one :promo_code, -> { PromoCode.order(:id) }, class_name: 'PromoCode',inverse_of: :product
belongs_to :product, inverse_of: :promo_code