[ACCEPTED]-How to get activerecord associations via reflection-activerecord

Accepted answer
Score: 93

Model.reflections gives information about a model's associations. It 10 is a Hash keyed on the association name. e.g.

Post.reflections.keys # => ["comments"]

Here 9 is an example of some of the information 8 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 7 been updated to cover Rails 4.2 based on 6 MCB's answer and the comments below. In earlier 5 versions of Rails the reflection's foreign_key was 4 accessed using primary_key_name instead, and the keys for 3 the reflections may be symbols instead of 2 strings depending on how the association 1 was defined e.g. :comments instead of "comments".

Score: 20

For future Googlers in Rails 4 the answer 9 would now be:

Post.reflections[:comments].foreign_key # => "message_id"

Taken from here: https://stackoverflow.com/a/15364743/2167965

EDIT:

reflections, as 8 of 4.2, now takes strings instead of symbols 7 which is a fun bug to track down. If you 6 want to keep using symbols you should switch 5 to reflect_on_association(:assoc_name). Also note reflections are actually the public api which will 4 keep reporting things like HABTM, even though 3 it's all has many through under the hood. The 2 reflections Rails is actually using are 1 now in _reflections

More Related questions