如何获得通过反射ActiveRecord关联反射、如何获得、ActiveRecord

2023-09-09 22:02:52 作者:挥不去的思念

对于正常列,可以通过让他们列类方法。但是,协会可能被命名为东西如 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".

 
精彩推荐
图片推荐