How to get activerecord associations via reflection

后端 未结 3 743
孤街浪徒
孤街浪徒 2020-12-23 00:04

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

3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-23 00:25

    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"
    

    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".

提交回复
热议问题