1

I am new to Rails so bear with me…

I am trying to create a set of data related to 2 different models. I currently have the following models:

class M < ActiveRecord::Base
 belongs_to :u
 belongs_to :s
end

class U < ActiveRecord::Base
 has_many :m
 has_many :s, :through => m:
end

class S < ActiveRecord::Base
 has_many :m
 has_many :u, :through => m;
end

In the system, the user can create many Us and Ss. But when creating an M it should make sure that there exist a reference to an "u" and an "s".

I know i can do the following:

m1 = M.create()
u1.ms << m1
s1.ms << m1

Which has all the appropriate reference, is there a better way?

machunter
  • 967
  • 1
  • 11
  • 27

1 Answers1

0

You should be able to do either one_u.s = one_s or one_s.u = one_u.

According to the Rails Guides, new M models will be managed by ActiveRecord. You can just set the attribute like a common has_many association, and the M rows will be created (and deleted) along with it.

Matheus Moreira
  • 17,106
  • 3
  • 68
  • 107
  • I am confused. where is the reference m1 in your example? Do you mean:u1.s = s1? Since :s in U is a "has_many" collection, will assignment do the job? – machunter Apr 19 '11 at 06:43