gpt4 book ai didi

ruby-on-rails - Rails 4 - 销毁 HABTM 记录导致 UndefinedTable

转载 作者:太空宇宙 更新时间:2023-11-03 16:47:12 29 4
gpt4 key购买 nike

我在事件和用户之间有一个 has_and_belongs_to_many 关系。

用户.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

事件.rb

class Event < ActiveRecord::Base
rolify
has_and_belongs_to_many :users, join_table: :events_users
end

当我想删除一个事件时,我会做两件事:

  1. 删除所有关联(从 events_users 表)
  2. 销毁事件(从事件表)

所以我写了这段代码来实现:

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

清除连接表中的关联效果很好 (@event.users.clear)。

当它试图销毁实际事件 (@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

它似乎在寻找“events_roles”表,但我不明白为什么。

(events_users 是有道理的,但是 events_roles 是出乎意料的)

感谢您的帮助。

最佳答案

这将与您在事件类中的“rolify”相关。

class Event < ActiveRecord::Base
rolify
...

这是 Rolify gem,它可能会在数据库中生成额外的表/字段。

关于ruby-on-rails - Rails 4 - 销毁 HABTM 记录导致 UndefinedTable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30966001/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com