views:

28

answers:

1

I have a simple model:

class User < ActiveRecord::Base
   has_and_belongs_to_many :roles
end

class Role < ActiveRecord::Base
   has_and_belongs_to_many :users
end

I have created a simple join table:

class CreateUsersRoles < ActiveRecord::Migration
  def self.up
    create_table :users_roles, :id => false do |t|
      t.integer :user_id
      t.integer :role_id

      t.timestamps
    end
  end

  def self.down
    drop_table :users_roles
  end
end

After migration, shema.rb is following:

create_table "roles", :force => true do |t|
    t.string   "name"
    t.datetime "created_at"
    t.datetime "updated_at"
end

create_table "users", :force => true do |t|
    t.string   "login"
    t.string   "password"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

create_table "users_roles", :id => false, :force => true do |t|
  t.integer  "user_id"
  t.integer  "role_id"
  t.datetime "created_at"
  t.datetime "updated_at"
end

The entries are presented here in the same order, as in "schema.rb"

I arranged fixtures in following way:

# roles.yml 
user:
  name: user

admin:
  name: admin

moderator:
  name: moderator

# users.yml
User1:
  login: User1
  password: User1
  roles: user

User2:
  login: User2
  password: User2
  roles: admin, moderator

User3:
  login: User3
  password: User3
  roles: moderator

And got a problem: on "rake db:fixtures:load" rails complains about name of a join table:

SQLite3::SQLException: no such table: roles_users: DELETE FROM "roles_users" WHERE 1=1

The question is - why it expects "roles_users", while the table is "users_roles" ?

+2  A: 

When Rails creates the association for the join table it expects the models to be in alphabetical order. Since r comes before u, it creates it as roles_users.

I suggest that you rename the join table, alternatively, you can add :join_table => "users_roles" to both associations.

Jimmy Stenke
Thanks a lot !! It works !
AntonAL