Rails 5 is inserting instead of updating when changing the value of attribute in the join table

Viewed 576

I have a HABTM relationship using a has_many :through association. I'm having trouble updating the attribute in the join table, because instead of updating the record it just inserts a new record in the table, creating duplicates.

I tried using the UNIQUE constraint when creating the index and adding a validation, but now when I update a record I get a validation error or the error: ActiveRecord::RecordNotUnique in BatchesController#update Mysql2::Error: Duplicate entry

To provide some context:

  • I have 4 tables: manufacturing_orders, order_products, batches and batches_order_products (join table).
  • A manufacturing_order have many order_products.
  • Also a manufacturing_order have many batches.
  • Batches have many order_products.
  • When I create a batch I copy all the order_products that belongs to the same manufacturing_order, and in the form I can assign a quantity for each of then.

So creating looks like working fine, but when I update any quantity it just inserts the whole relation again instead of updating the existing one.

Model manufacturing_order.rb:

class ManufacturingOrder < ApplicationRecord
  has_many :batches, inverse_of: :manufacturing_order, dependent: :destroy
  has_many :order_products, inverse_of: :manufacturing_order, dependent: :destroy

  accepts_nested_attributes_for :order_products
  accepts_nested_attributes_for :batches
end

Model order_product.rb:

class OrderProduct < ApplicationRecord

  belongs_to :manufacturing_order

  has_many :batches_order_products
  has_many :batches, :through => :batches_order_products
end

Model batch.rb:

class Batch < ApplicationRecord
  belongs_to :manufacturing_order

  has_many :batches_order_products
  has_many :order_products, :through => :batches_order_products

  accepts_nested_attributes_for :batches_order_products
end

Model batches_order_product.rb:

class BatchesOrderProduct < ApplicationRecord
  belongs_to :batch
  belongs_to :order_product

  validates :batch_id, uniqueness: { scope: :order_product_id }
end

Controller batches_controller.rb:

class BatchesController < ApplicationController
  def new
    manufacturing_order = ManufacturingOrder.find(params[:manufacturing_order_id])
    order_products = manufacturing_order.order_products
    @batch = Batch.new({
      manufacturing_order: manufacturing_order,
      order_products: order_products
    })
  end

  def create
    @batch = Batch.new(load_params)
    if @batch.save
      flash[:notice] = crud_success
      redirect_to action: :index
    else
      flash[:error] = @batch.errors.full_messages.to_sentence
      render action: :new
    end
  end

  def edit
    @batch = Batch.find(params[:id])
  end

  def update
    @batch = Batch.find(params[:id])
    if @batch.update_attributes(load_params)
      flash[:notice] = crud_success
      redirect_to action: :index
    else
      flash[:error] = @batch.errors.full_messages.to_sentence
      render action: :edit
    end
  end

  private
  def load_params
    params.require(:batch)
    .permit(:name,
      :date,
      :manufacturing_order_id,
      :status,
      order_products: [],
      order_products_ids: [],
      batches_order_products_attributes: [:id, :quantity, :order_product_id]
      )
  end
end

This is the form in batches:

  = bootstrap_form_for([@batch.manufacturing_order, @batch]) do |f|
    = f.hidden_field :manufacturing_order_id
       = f.text_field :name, label: 'Name'
        = f.text_field :date
    table
      thead
        tr
          th= "Product"
          th= "Quantity"
    tbody
      = f.fields_for :batches_order_products do |bop|
        = bop.hidden_field :order_product_id
      tr
        td
          = bop.object.order_product.name
        td
          = bop.text_field :quantity

  = f.submit 'Save'

Any help will be very much appreciated. Thanks!

UPDATE: These are the params passed when submitting the edit form. Any clue?

{"utf8"=>"✓",
 "_method"=>"patch",
 "batch"=>
  {"manufacturing_order_id"=>"8",
   "name"=>"MAS",
   "date"=>"07/05/2020",
   "batches_order_products_attributes"=>
    {"0"=>{"order_product_id"=>"12", "quantity"=>"77777777", "id"=>""},
     "1"=>{"order_product_id"=>"13", "quantity"=>"9.0", "id"=>""},
     "2"=>{"order_product_id"=>"14", "quantity"=>"7.0", "id"=>""}}},
 "commit"=>"Guardar",
 "manufacturing_order_id"=>"8",
 "id"=>"7"}

EDIT 2: I updated the nested form to include the id in a hidden field like this:

= f.fields_for :batches_order_products do |bop|
  = bop.hidden_field :order_product_id
  = bop.hidden_field :id, value: @batch.id

  = bop.object.order_product.name
  = bop.text_field :quantity, label: ''

BUT now Rails complains of this when updating:

ActiveRecord::StatementInvalid in BatchesController#update

Mysql2::Error: Unknown column 'batches_order_products.' in 'where clause': SELECT `batches_order_products`.* FROM `batches_order_products` WHERE `batches_order_products`.`batch_id` = 9 AND `batches_order_products`.`` IN ('9', '9', '9', '9', '9') 

I don't know why Rails adds that last weird part in SQL query.

1 Answers

So I've finally figured it out.

The problem was that the join table needed an ID column to reference to. The table had an index of batch_id and order_product_id but for some reason it didn't work and ActiveRecord was looking for an ID. Adding it solved the problem.

Thanks to @max for giving some points to look at.

class AddIndexToBatchesOrderProductsJoinTable < ActiveRecord::Migration[5.2]
  def change
    # add_index :batches_order_products, [:batch_id, :order_product_id], unique: true
    add_column :batches_order_products, :id, :primary_key
  end
end
Related