問題描述
在 Rails 中,我可以在另一個模型的模型上設置 has_many 關係嗎? (In Rails, can I set a has_many relation on a model from another model?)
Is there any way I can set both halves of a belongs_to/has_many relation in just one of the models? So I want do something like:
class A < ActiveRecord::Base
end
class B < ActiveRecord::Base
belongs_to :a
A.has_many :b
end
Obviously this doesn't work (or I would have used it) but I hope it explains what I mean...
參考解法
方法 1:
I'm not sure why you'd want to, but assuming you have a great reason...
has_many
is just a class method defined in ActiveRecord::Base so calling A.has_many :b
should work.
You might have issues however in development with loading order. If you load up the example you gave and called a = A.new
, the class B has never been loaded, so a
has no idea that A
has many B
. In production, where the entire class list is loaded on start, this won't be a problem. In development you can get around it by using a require
statement, however, you are then coupling the two files together pretty strongly.
I haven't tried it, but in theory, that's the only thing I can think of that is preventing your setup above from working.
(by Kevin Hughes、jesse reiss)