Rails 方法获取模型的关联名称
有没有办法找出模型有哪些关联?以这两个模型为例:
class Comment < ActiveRecord::Base
belongs_to :commentable
end
class Post < ActiveRecord::Base
has_many :comments
belongs_to :user
end
我正在寻找类似的东西:
Post.has_many #=> ['comments', ...]
Post.belongs_to # => ['user']
Comment.belongs_to # => ['commentable']
Is there a way to find out what associations a model has? Take these 2 models:
class Comment < ActiveRecord::Base
belongs_to :commentable
end
class Post < ActiveRecord::Base
has_many :comments
belongs_to :user
end
I'm looking for something like:
Post.has_many #=> ['comments', ...]
Post.belongs_to # => ['user']
Comment.belongs_to # => ['commentable']
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在寻找
reflect_on_all_associations
。简而言之:
...将给出所有
has_many
关联的数组(具有name
等属性的对象)。You're looking for
reflect_on_all_associations
.So in short:
...will give an array (of object with attributes like
name
, etc) of allhas_many
associations.下面将列出特定 Post 实例的所有关联。
The following will list all the associations for a particular instance of Post.