Rails构建belongs_to关联“必须存在”错误

Vic*_*una 6 ruby ruby-on-rails ruby-on-rails-5

我正在尝试在rails 中的belongs_to 模型关联中构建一个has_many 模型。关联是正确的,但显示错误“必须存在”。我尝试添加可选项:true,但它似乎不起作用。

楷模

class User::Product < ApplicationRecord
  has_one: :promo_code
end

class User::PromoCode < ApplicationRecord
  belongs_to: :product, optional: true
  accepts_nested_attributes_for :product
end
Run Code Online (Sandbox Code Playgroud)

促销代码控制器

def new
  @promo_code = User::PromoCode.new
  @product.build_product
end

def create
  @promo_code = User::PromoCode.new(promo_code_params)
  @promo_code.save
end

def promo_code_params
  params.require(:user_promo_code).permit(:product_id, :product_attributes => [:name])
end
Run Code Online (Sandbox Code Playgroud)

形式

form_with(model: promo_code) do |form|
  form.fields_for :product do |f|
    f.text_field :name
  end
end
Run Code Online (Sandbox Code Playgroud)

当表单保存时,出现错误,提示“必须存在”,我假设它指的是belongs_to中的外键。

我可能做错了什么有什么想法吗?我认为上面的代码是我关于这个问题的唯一相关代码。

SRa*_*ack 8

查看@engineersmnky 链接的问题,看起来这似乎是使用accepts_nested_attributes_for.

inverse_of这可以通过使用澄清双向关系的选项来解决:

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
Run Code Online (Sandbox Code Playgroud)

尝试一下,看看是否可以解决您的问题。

  • 由于某种原因,它以前从未抱怨过,但问题出在代码的不同部分。改变了这一点,无论有或没有逆,关系都有效。感谢您的帮助! (2认同)