0

我有这个 Rails 3.2 应用程序运行良好。我按照以下步骤安装了Rolify :

  1. 添加gem "rolify"到 Gemfile
  2. bundle install
  3. rails g rolify:role
  4. 检查新的迁移、新文件和修改的文件(由上面的命令生成/修改)。
  5. rake db:migrate

此时,我尝试创建/编辑用户并收到以下错误:

NoMethodError in UsersController#create

undefined method `user_id' for #<User:0x007f8f21f168e8>

请注意,在我安装 Rolify 之前,一切正常,所以问题来自 Rolify。

以下是有问题的迁移、新文件和修改后的文件:

新的迁移:

class RolifyCreateRoles < ActiveRecord::Migration
  def change
    create_table(:roles) do |t|
      t.string :name
      t.references :resource, :polymorphic => true

      t.timestamps
    end

    create_table(:users_roles, :id => false) do |t|
      t.references :user
      t.references :role
    end

    add_index(:roles, :name)
    add_index(:roles, [ :name, :resource_type, :resource_id ])
    add_index(:users_roles, [ :user_id, :role_id ])
  end
end

新型号:

class Role < ActiveRecord::Base
  has_and_belongs_to_many :users, :join_table => :users_roles
  belongs_to :resource, :polymorphic => true
end

修改后的模型:

class User < ActiveRecord::Base
  rolify
  has_secure_password

  has_many :issues
  acts_as_tenant(:client)

  attr_accessible :email, :password, :password_confirmation, :username

  validates :username, presence: true,
                       length: { within: 4..50 },
                       format: { with: /(?:[\w\d]){4,255}/ }
  validates_uniqueness_to_tenant :username, case_sensitive: false

  validates :email, presence: true,
                    uniqueness: { case_sensitive: false },
                    length: { within: 8..255 },
                    format: { with: /^[-a-z0-9_+\.]+\@([-a-z0-9]+\.)+[a-z0-9]{2,4}$/i }

  validates :password, presence: true, on: :create,
                       confirmation: true,
                       length: { within: 4..255 }

  validates :password_confirmation, presence: true, on: :create

  # NOTE: Used by SimpleForm to display the dropdown proerply
  def to_label
    "#{username}"
  end
end

您可以在Github存储库中找到项目中的其余文件

请问有谁知道错误来自哪里?

4

1 回答 1

3

user_id发生此错误是因为acts_as_tenant (错误地)为模型上的字段创建验证User。如果你在里面运行这个代码,你可以看到这个验证器rails c

 User._validators

我建议切换到看起来比acts_as_tenant 维护得更好的公寓gem。

于 2012-07-24T22:52:05.563 回答