0

我在使用 Devise 进行身份验证的 RoR 应用程序中有用户模型(在 PostgreSQL 数据库中)。现在我想邀请用户,所以我决定使用devise_invitable gem。按照安装指南,我做了:

  1. 将 gem 'devise_invitable' 添加到我的 Gemfile
  2. 运行 rails generate devise_invitable:install
  3. 运行 rails generate devise_invitable User

比我尝试运行上面生成的迁移(它是这个 gem 给出的默认值,它看起来像:)

class DeviseInvitableAddToUsers < ActiveRecord::Migration
  def up
    change_table :users do |t|
      t.string     :invitation_token, :limit => 60
      t.datetime   :invitation_sent_at
      t.datetime   :invitation_accepted_at
      t.integer    :invitation_limit
      t.references :invited_by, :polymorphic => true
      t.index      :invitation_token, :unique => true # for invitable
      t.index      :invited_by_id
    end

    # And allow null encrypted_password and password_salt:
    change_column_null :users, :encrypted_password, true
  end

  def down
    change_table :users do |t|
      t.remove_references :invited_by, :polymorphic => true
      t.remove :invitation_limit, :invitation_sent_at, :invitation_accepted_at,   :invitation_token
    end
  end
end

但是,在运行迁移时,我得到:

==  DeviseInvitableAddToUsers: migrating ======================================
-- change_table(:users)
rake aborted!
An error has occurred, this and all later migrations canceled:

PG::Error: ERROR:  relation "invited_bies" does not exist
: ALTER TABLE "users" ADD CONSTRAINT fk_users_invited_by_id FOREIGN KEY ("invited_by_id") REFERENCES "invited_bies" ("id")

我不是 PostgreSQL 中的大师,它是外键,但看起来应该有邀请表,不是吗?但它不是被创造出来的。所以,我对这一切有点困惑。

我的用户设计模型:

devise :invitable, :database_authenticatable, :recoverable, :rememberable, token_authenticatable,:trackable, :authentication_keys => [:email]

这些字段:invitable, :database_authenticatable是由生成脚本添加的。

4

2 回答 2

2

你在使用 Schema_plus Gem 吗?

如果您正在使用它,此 Gem 将尝试根据任何字段的 _id 创建外键关系。

您需要为这样的字段禁用此功能

t.integer  :invited_by_id,  foreign_key: false

让我知道是否是这种情况。

于 2013-05-05T06:22:24.060 回答
2

你的问题在这里:

3. Run rails generate devise_invitable

那应该是

rails generate devise_invitable MODEL

并且您将 MODEL 替换为您的设计模型的名称。那可能是用户,但它应该是您正在设计为您管理的模型的名称。因此,如果您使用 User 作为模型:

rails generate devise_invitable User

因为您没有提供模型名称,所以生成器正在生成无效迁移,这可能是一个错误,您可能需要报告)。当您的迁移尝试在邀请和发出邀请“invited_by”的“用户”之间创建外键关系时,它会失败,因为它不知道要引用哪个表。

编辑:2013-05-04:

您的用户模型是否也包含以下内容:

 has_many :invitations, :class_name => self.to_s, :as => :invited_by
于 2013-05-03T14:57:28.130 回答