I have a has_and_belongs_to_many relationship between Events and Users.
user.rb
class User < ActiveRecord::Base
rolify
has_and_belongs_to_many :events, join_table: :events_users
after_create :assign_default_role
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
def assign_default_role
add_role(:basic)
end
end
event.rb
class Event < ActiveRecord::Base
rolify
has_and_belongs_to_many :users, join_table: :events_users
end
When I want to delete an Event I do two things:
- remove all associations (from events_users table)
- destroy the Event (from events table)
So I wrote this code to accomplish that:
events_controller.rb
def destroy
@event.users.clear #remove all associations
@event.destroy #destroy event
respond_to do |format|
flash[:success] = 'Event was successfully deleted.'
format.html { redirect_to events_url }
format.json { head :no_content }
end
end
Clearing associations in the join table works fine (@event.users.clear).
I get an error when it tries to destroy the actual Event (@event.destroy).
(0.7ms) BEGIN
SQL (0.4ms) DELETE FROM "events_users" WHERE "events_users"."event_id" = $1 [["event_id", 13]]
PG::UndefinedTable: ERROR: relation "events_roles" does not exist
LINE 5: WHERE a.attrelid = '"events_roles"'::regclass
^
: SELECT a.attname, format_type(a.atttypid, a.atttypmod),
pg_get_expr(d.adbin, d.adrelid), a.attnotnull, a.atttypid, a.atttypmod
FROM pg_attribute a LEFT JOIN pg_attrdef d
ON a.attrelid = d.adrelid AND a.attnum = d.adnum
WHERE a.attrelid = '"events_roles"'::regclass
AND a.attnum > 0 AND NOT a.attisdropped
ORDER BY a.attnum
(0.3ms) ROLLBACK
ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR: relation "events_roles" does not exist
LINE 5: WHERE a.attrelid = '"events_roles"'::regclass
^
: SELECT a.attname, format_type(a.atttypid, a.atttypmod),
pg_get_expr(d.adbin, d.adrelid), a.attnotnull, a.atttypid, a.atttypmod
FROM pg_attribute a LEFT JOIN pg_attrdef d
ON a.attrelid = d.adrelid AND a.attnum = d.adnum
WHERE a.attrelid = '"events_roles"'::regclass
AND a.attnum > 0 AND NOT a.attisdropped
ORDER BY a.attnum
It appears to be looking for an "events_roles" table and I don't understand why.
(events_users makes sense, but events_roles is out of the blue)
Help is appreciated.
This will be related to the 'rolify' you have in your Event class.
This is the Rolify gem, which probably generates extra tables/fields in the DB.