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.
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.
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 forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.