ActiveRecord relationship with name different from table

I’m trying to give a company employees that are stored in the users
table. What I’ve done is:

class Company < ActiveRecord::Base
has_many :employees, :class_name => ‘User’
end

class User < ActiveRecord::Base
belongs_to :company
end

But this doesn’t seem to work.

u = User.find(1)
c = Company.new
c.name = ‘Test’
c.save # true
u.company = c
c.employees # []
u.save # false

And:
c = Company.new
c.name = ‘Test’
c.save # true
c.employees << User.find(1)
c.save # false
u.company # nil

What am I missing here?

db (simplified):
create table companies (
id int not null,
name varchar(100) not null,
primary key(id)
);

create table users (
id int not null,
username varchar(100) not null,
company_id int,
primary key(id),
foreign key(company_id) references companies(id)
);

Has anyone got a clue here? I’m really stuck…

the only thing I can think of is that maybe you need to add this to your
has_many line:

has_many :employees, :class_name => “User”, :foreign_key => “company_id”

that or add the foreign_key to the User class. When I write my apps,
just
to be sure the reference is correct, i add the foreign key to both of
the
models if I’m not using the default foreign key scheme. I figure it
doesn’t
hurt. Otherwise just try it in each one individually and see which one
works.

On 12/11/06, Christian J. [email protected]
wrote:

Has anyone got a clue here? I’m really stuck…


Posted via http://www.ruby-forum.com/.


Mike W.
Web D.
UW-Eau Claire

On Dec 11, 3:42 pm, Christian J.
[email protected] wrote:

Has anyone got a clue here? I’m really stuck…

Hrm. Here’s what I’ve got.

Migration:

create_table "companies" do |t|
  t.column "name", :string
end
create_table "users" do |t|
  t.column "name", :string
  t.column "company_id", :integer
end

Models:

class User < ActiveRecord::Base
belongs_to :company
end

class Company < ActiveRecord::Base
has_many :employees, :class_name => “User”
end

And, on the console:

u = User.create #=> ok
c = Company.create #=> ok
u.company = c #=> ok
u.company #=> shows Company c
c.employees #=> []
u.save #=> true
c.reload #=> ok (need to refresh Company c’s
data from the db)
c.employees #=> [ User u ]

This is Rails 1.1.6, Ruby 1.8.4, Sqlite3, Mac OS X.

Best,

-r

That did the trick, thanks! I’m pretty new to all this, and had of
course forgotten all about reload… It works perfectly now!

[email protected] wrote:

u = User.create #=> ok
c = Company.create #=> ok
u.company = c #=> ok
u.company #=> shows Company c
c.employees #=> []
u.save #=> true
c.reload #=> ok (need to refresh Company c’s
data from the db)
c.employees #=> [ User u ]