Home > Software engineering >  What's the right way to update a record using has_many, through table? Update a record doesn�
What's the right way to update a record using has_many, through table? Update a record doesn�

Time:06-18

Rails v6.1.4

So I got the 3 tables contacts, lists, and the bridge table between two tables called multicats.

    create_table :multicats, id: false do |t|
      t.belongs_to :user
      t.belongs_to :list
      t.belongs_to :contact
    end

    create_table :contacts do |t|
      t.belongs_to :user
      t.string :email
      t.string :first_name
      t.timestamps
    end

    create_table :lists do |t|
      t.belongs_to :user
      t.string :name
      t.timestamps
    end
class Contact < ApplicationRecord
  has_many :multicats
  has_many :lists, :through => :multicats, dependent: :destroy
end
class List < ApplicationRecord
  has_many :multicats
  has_many :contacts, :through => :multicats, dependent: :destroy
end

When I update a record I got an error: ActiveRecord::UnknownPrimaryKey in ContactsController#update Unknown primary key for table multicats in model Multicat.

 # PATCH/PUT /contacts/1 or /contacts/1.json
  def update
    respond_to do |format|
      if @contact.update(first_name:  contact_params[:first_name], :email => contact_params[:email])
        mc=Multicat.update(Multicat.list_id,@contact.id, {:list_id => contact_params[:list]})
        # mc.update!
        format.html { redirect_to contacts_url, notice: "Contact was successfully updated." }
        format.json { render :show, status: :ok, location: @contact }
      else
        format.html { render :edit, status: :unprocessable_entity }
        format.json { render json: @contact.errors, status: :unprocessable_entity }
      end
    end
  end

What's the right way to update a record when it's got has_many, through a table ?

CodePudding user response:

By default, Rails will assign id as the primary key. In your migration, the multicast :id was set to false, which result in no primary key: for multicasts table.

ActiveRecords needs primary_key to do an update operation. So, when you call update method, it will find no primary_key reference and throw ActiveRecord::UnknownPrimaryKey error.

If you intentionally remove the id and want to assign another name you have to provide another :primary_key for your multicast table.

  • Related