在 Rails 中,我可以在另一个模型的模型上设置 has_many 关系吗?
有什么方法可以在其中一个模型中设置belongs_to/has_many 关系的两半吗?所以我想做一些类似的事情:
class A < ActiveRecord::Base
end
class B < ActiveRecord::Base
belongs_to :a
A.has_many :b
end
显然这不起作用(或者我会使用它),但我希望它能解释我的意思......
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...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不确定你为什么想要这样做,但假设你有一个很好的理由...
has_many
只是 ActiveRecord::Base 中定义的一个类方法,因此调用A.has_many : b
应该可以工作。然而,在开发过程中,您可能会遇到加载顺序问题。如果您加载给出的示例并调用
a = A.new
,则类 B 从未加载过,因此a
不知道A
code> 有很多B
。在生产中,整个类列表在启动时加载,这不会成为问题。在开发中,您可以使用require
语句来解决这个问题,但是,您随后会将两个文件非常紧密地耦合在一起。我还没有尝试过,但从理论上讲,这是我能想到的唯一会阻止你上面的设置工作的事情。
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 callingA.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, soa
has no idea thatA
has manyB
. 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 arequire
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.