Skip to content

Join table cannot update or destroy throw error of no primary key #25347

Closed
@starkshaw

Description

@starkshaw

Steps to reproduce

Have models as follow:

class Event < ApplicationRecord
  belongs_to :deal
  has_many :events_users
  has_many :users, through: :events_users
end

class Deal < ApplicationRecord
  belongs_to :team
  has_many :deals_users
  has_many :users, through: :deals_users
  has_many :events
end

class Team < ApplicationRecord
  has_many :deals
  has_many :team_users
  has_many :users, through: :team_users
end

class User < ApplicationRecord
  has_one :team, through: :team_user
  has_one :team_user
  has_and_belongs_to_many :deals
  has_and_belongs_to_many :events
end

class EventsUser < ApplicationRecord
  belongs_to :event
  belongs_to :user
  validates_uniqueness_of :event_id, scope: :user_id
  enum status: [:pending, :accepted, :maybe, :rejected]
end

class DealsUser < ApplicationRecord
  belongs_to :user
  belongs_to :deal
  validates_uniqueness_of :deal_id, scope: :user_id
end

class TeamUser < ApplicationRecord
  belongs_to :user
  belongs_to :team
  validates_uniqueness_of :team_id, scope: :user_id
  validates_uniqueness_of :user_id
end

Expected behavior

The join tables, EventsUser, DealsUser, TeamUser can be updated or deleted.

Actual behavior

It can only be created, the update will throw

ActiveRecord::UnknownPrimaryKey: Unknown primary key for table events_users in model EventsUser.
Can not validate uniqueness for persisted record without primary key.

and destroy will throw

NoMethodError: undefined method `to_sym' for nil:NilClass

These following are my testing procedures in rails c.

eu = EventsUser.first
eu.status = "maybe"
eu.save (throw update error)
eu.destroy (throw destroy error)
eu (it exists)
eu.status (return the status)

status is an enum in model, and defined in migration as such:

t.integer :status, default: 0

System configuration

Rails version:
Rails 5.0.0.rc1
Ruby version:
ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-darwin15]

Reference

#21304

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions