R – How to load data in a Ruby on Rails Join Table

fixturesjoinruby-on-rails

I have the following join table that works:

class CreateRolesUsers < ActiveRecord::Migration
  def self.up
    create_table :roles_users,:id => false do |t|
      t.integer :role_id, :null => false
      t.integer :user_id, :null => false
    end    
  end

  def self.down
    drop_table :roles_users
  end
end

But I don't know how to load by default some data (syntax), I try that:

roleUser = RoleUser.create(:role_id => 2,:user_id => 1)
roleUser.save!

It does not work, is it RoleUser… or something else to use? RolesUser…etc.

Best Solution

That's provided that you have a model named RolesUser.

If you have a habtm association, the model is probably not there.

One way of loading roles could be;

user = User.create :name => 'John'
role = Role.create :name => 'admin'

user.roles << role