Many to many, error on relation

two tables, users and languages,

one user may have many languages, one language may belong to many users.
so, I create the joint table users_languages with user_id and
language_id only.

class User < ActiveRecord::Base
has_and_belongs_to_many :languages
end

class Language < ActiveRecord::Base
has_and_belongs_to_many :users
end

class UsersLanguages < ActiveRecord::Base
belongs_to :users
belongs_to :languages
end

I also create one sample user data into users tables and one sample
language data into languages table. nothing in joint table
users_languages.

then, I go to console to test:

if I use the following code, everything is fine.

l=Language.new
u=User.new
u.languages << l

but when I use the real data, still under console,

l=Language.find(1)
u=User.find(1)
u.languages << l

when I am at the third line, I will get an error message like this:

ActiveRecord::StatementInvalid: PGError: ERROR: relation
“languages_users” does not exist
: SELECT a.attname, format_type(a.atttypid, a.atttypmod),
d.adsrc, a.attnotnull
FROM pg_attribute a LEFT JOIN pg_attrdef d
ON a.attrelid = d.adrelid AND a.attnum = d.adnum
WHERE a.attrelid = ‘languages_users’::regclass
AND a.attnum > 0 AND NOT a.attisdropped
ORDER BY a.attnum

any reason for that? thanks for any help.

Surfman J. wrote:

class UsersLanguages < ActiveRecord::Base
belongs_to :users
belongs_to :languages
end

Rails expects the join table to be named languanges_users. Also, you
don’t want a model for this table, you simple create a migration:

class LanguagesUsers < ActiveRecord::Migration
def self.up
create_table :languages_users, :id => false do |t|
t.column :language_id, :integer, :null => false
t.column :user_id, :integer, :null => false
end
end

def self.down
drop_table :languages_users
end
end

Drew O. wrote:

Rails expects the join table to be named languanges_users. Also, you
don’t want a model for this table, you simple create a migration:

class LanguagesUsers < ActiveRecord::Migration
def self.up
create_table :languages_users, :id => false do |t|
t.column :language_id, :integer, :null => false
t.column :user_id, :integer, :null => false
end
end

def self.down
drop_table :languages_users
end
end

Thanks. It fixes my problem.

I am totally new to ROR, how can I know when I have to use
languages_users rather than users_languages?

Is there any tutorial for naming convention? thanks.

I am totally new to ROR, how can I know when I have to use
languages_users rather than users_languages?

It’s based on which word comes first in the alphabet, hence
languages_users rather than users_languages.

-Drew

Yes. There are tons of tutorials, books, and such. Also there is
always the Rails and Ruby API.
Agile web development with rails has an excellant chapter on
relationship so does the RoR website’s How To section.

On Feb 20, 9:04 am, Surfman J. [email protected]