如何通过反射获得 activerecord 关联 [英] How to get activerecord associations via reflection
问题描述
对于普通列,您可以通过 columns
类方法获取它们.但是,如果在关系方法中设置了 foreign_key
选项,则关联可能会被命名为完全不同的名称.例如,给定
For normal columns, you can get at them via the columns
class method. However, associations may be named something quite different if the foreign_key
option is set in the relationship method. For example, given
class Post
has_many :comments, :foreign_key => :message_id # this is a contrived example
end
如果我做了Post.column_names
,我可以得到message_id
,但是有没有办法得到comments
?
if I did Post.column_names
I could get at message_id
, but is there any way to get comments
?
推荐答案
Model.reflections
提供有关模型关联的信息.它是一个以关联名称为键的 Hash
.例如
Model.reflections
gives information about a model's associations. It is a Hash
keyed on the association name. e.g.
Post.reflections.keys # => ["comments"]
以下是它可以用来访问的一些信息的示例:
Here is an example of some of the information it can be used to access:
Post.reflections["comments"].table_name # => "comments"
Post.reflections["comments"].macro # => :has_many
Post.reflections["comments"].foreign_key # => "message_id"
<小时>
注意:此答案已更新以涵盖基于 MCB 的 Rails 4.2回答和下面的评论.在早期版本的 Rails 中,反射的 foreign_key
是使用 primary_key_name
访问的,反射的键可能是符号而不是字符串,这取决于关联的定义方式,例如:comments
而不是 "comments"
.
Note: this answer has been updated to cover Rails 4.2 based on MCB's answer and the comments below. In earlier versions of Rails the reflection's foreign_key
was accessed using primary_key_name
instead, and the keys for the reflections may be symbols instead of strings depending on how the association was defined e.g. :comments
instead of "comments"
.
这篇关于如何通过反射获得 activerecord 关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!