1
我是新來的鐵軌,所以忍受着我...管理Rails ActiveRecord關聯的正確方法是什麼?
我想創建一組數據相關的2個不同的模型。我目前有以下型號:
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
在系統中,用戶可以創建很多Us和Ss。但是在創建M時,應確保存在對「u」和「s」的引用。
我知道我能做到以下幾點:
m1 = M.create()
u1.ms << m1
s1.ms << m1
其中有所有適當的參考,有沒有更好的辦法?
我很困惑。你的例子中的參考m1在哪裏?你的意思是:u1.s = s1?因爲:U中的s是一個「has_many」集合,分配會完成這項工作嗎? – machunter 2011-04-19 06:43:11