I am trying to build a has_many model in the belongs_to model association in rails. The association is correct, but it shows error "must exist". I tried putting the optional: true, but it does not seem to be working.
Models
class User::Product < ApplicationRecord
has_one: :promo_code
end
class User::PromoCode < ApplicationRecord
belongs_to: :product, optional: true
accepts_nested_attributes_for :product
end
PromoCodesController
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
form
form_with(model: promo_code) do |form|
form.fields_for :product do |f|
f.text_field :name
end
end
When the form saves an error appears saying "must exist", which I am assuming is referring to the foreign key in belongs_to.
Any ideas in what I can be doing wrong? I think the code above is the only relevant code that I have regarding this issue.
Product
as well as aUser::Product
? – Knighthoodoptional: true
should have solved this – Knighthood