Rails 如何查询关联定义
我有很多动态代码,它们将复杂的关系保存在字符串中。 例如:
"product.country.continent.planet.galaxy.name"
我如何检查这些关系是否存在? 我想要一个如下的方法:
raise "n00b" unless Product.has_associations?("product.country.planet.galaxy")
我怎样才能实现这个?
I have a lot of dynamic code which keeps complex relations in a string.
ex:
"product.country.continent.planet.galaxy.name"
How can I check if these relations exist?
I want a method like the following:
raise "n00b" unless Product.has_associations?("product.country.planet.galaxy")
How could I implement this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
试试这个:
Try this:
如果这些是活动记录关联,则可以执行以下操作:
这将告诉您此特定路径是否具有所有关联。
If these are active record associations, here's how you can do it:
And this will tell you if this specific path has all the associations.
如果您确实将 AR 关联存储在这样的字符串中,则放置在初始化程序中的这段代码应该可以让您执行您想要的操作。我一生都无法弄清楚你为什么要这样做,但我相信你有你的理由。
这样,您需要省略初始模型名称,因此对于您的示例,它将是:
If indeed you are storing the AR associations in a string like that, this code placed in an initializer should let you do what you want. For the life of me I can't quite figure out why you'd want to do this, but I trust you have your reasons.
With this you'll need to leave off the initial model name, so for your example it would be: