Robert Audi
Robert Audi

Reputation: 8477

Rails 3.2 + Rolify: Application breaks after installing Rolify (Bug?)

I have this Rails 3.2 application running fine. I installed Rolify by following the steps below:

  1. Add gem "rolify" to the Gemfile
  2. Run bundle install
  3. Run rails g rolify:role
  4. Check the new migrations, the new files and the modified files (generated/modified by the command above).
  5. Run rake db:migrate

At this point, I try to create/edit a User and I get the following error:

NoMethodError in UsersController#create

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

Note that before I installed Rolify, everything was working fine, so the problem comes from Rolify.

Here are the migration, the new file and the modified file in question:

The new migration:

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

The new model:

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

The modified model:

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

You can find the rest of the files in the project in the Github repo

Does anyone have a clue where the error comes from please?

Upvotes: 0

Views: 455

Answers (1)

Ryan Bigg
Ryan Bigg

Reputation: 107728

This error is happening because the acts_as_tenant is (mistakenly) creating a validation for a user_id field on your User model. You can see this validator if you run this code inside rails c:

 User._validators

I would recommend to switch to the apartment gem which appears to be more maintained than acts_as_tenant.

Upvotes: 3

Related Questions