我有一个has_和_belongs_很多事件和用户之间的关系。
用户.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

当我想删除一个事件时,我会做两件事:
删除所有关联(从事件用户表)
销毁事件(从事件表)
所以我写了这段代码来完成:
事件控制器.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

它似乎在寻找一个“事件/角色”表,我不明白为什么。
(事件用户是有道理的,但事件角色是出人意料的)
感谢您的帮助。

最佳答案

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

class Event < ActiveRecord::Base
  rolify
  ...

这是Rolifygem,它可能在db中生成额外的表/字段。

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

10-13 05:23