After adding an attribute to params

images_attributes: [:file] 

I attach the file and when I create a new product, an error occurs

 - Images product must exist 

What could be the snag?

Controller:

  def new @product = Product.new @product.images.build end def create @product = Product.new(product_params) @product.user = current_user if @product.save redirect_to @product else render 'new' end end private def product_params params.require(:product).permit(:name, :description, images_attributes: [:file]) end 

new.html.slim

 = f.fields_for :images do |i| = i.file_field :file 

In the product accepts_nested_attributes_for :images, reject_if: :all_blank model accepts_nested_attributes_for :images, reject_if: :all_blank

In the model image mount_uploader :file, ImageUploader

Associations are all registered. I use carriewave and Rails 5

    1 answer 1

    https://github.com/rails/rails/issues/25198

    In Rails 5.0, the belongs_to_required_my_default option belongs_to_required_my_default set to true by default. This means that the associated resource must already have been created.

    To circumvent this limitation, you can:

    • disable this option globally by setting Rails.application.config.active_record.belongs_to_required_by_default to false or

    • set optional: true in the belongs_to :product method of the Image model, in this case the check for the existence of the associated resource will be skipped, or

    • set inverse_of: :product in the has_many :images method of the Product model, in which case the resource will be automatically created.

    • Thank you very much) - Andrey