如何获得通过反射ActiveRecord关联 [英] How to get activerecord associations via reflection
问题描述
对于正常列,可以通过让他们列
类方法。但是,协会可能被命名为东西如 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
,但有什么办法让评论
?
if I did Post.column_names
I could get at message_id
, but is there any way to get comments
?
推荐答案
Model.reflections
提供有关模型的关联信息。这是一个散列
键入对联想的名字。例如,
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"
注意:的这个答案已经被更新,涵盖的Rails 4.2的基础上 MCB 的回答和下面的评论。在早期版本的Rails的反映的 foreign_key
使用被访问 primary_key_name
代替,并为反射的按键可能是符号,而不是串取决于该协会是如何定义的,例如:评论
评论
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屋!