查找模型上定义的所有 :has_many 关系
我有一个模型 User,它在 user.rb 中定义了许多关系,例如
has_many :posts, :dependent => :destroy
has_many :comments, :dependent => :destroy
... and others
如何以编程方式找到所有此类关系?也就是说,我希望能够通过 Rails 找到所有子模型,例如 Post、Comment 等,而不必手动查看 user.rb 文件。
我该怎么做?
I have a model User that has defined in user.rb many relationships like
has_many :posts, :dependent => :destroy
has_many :comments, :dependent => :destroy
... and others
How can I programmatically find all such relationships? That is I want to be able to do find all the child models like Post, Comment etc via Rails and not have to look at the user.rb file manually.
How can I do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您想要做的就是所谓的“反射”——您的软件可以在运行时动态地了解更多关于自身的信息。
在 Rails 中,ActiveRecord 支持这一点。请参阅 Reflection 方法。
根据文档添加,您可以调用
You 会返回一个对象数组,这些对象将为您提供有关 User 类的所有 has_many 关联的信息。
What you want to do is called "reflecting" -- whereby your software finds out more about itself, on the fly, at runtime.
In Rails, ActiveRecord supports this. See the Reflection methods.
Added per the docs, you'd call
You'd get back an array of objects that would give you info about all of the has_many associations of your User class.