How to get activerecord associations through reflection

For regular columns, you can get them using the method of the columns class. However, associations can be called completely different if the foreign_key parameter foreign_key specified in the relationship method. For example, given

 class Post has_many :comments, :foreign_key => :message_id # this is a contrived example end 

If I did Post.column_names , I could get message_id , but is there a way to get comments ?

+48
reflection ruby activerecord
Nov 13 2018-10-11
source share
3 answers

Model.reflections provides information on model associations. This Hash name is associated with the association name. eg.

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

Here is an example of some information that he can use 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 include Rails 4.2 based on the MCB response and comments below. In earlier versions of Rails, the foreign_key reverse reflection was available using primary_key_name instead, and the reflection keys could be characters instead of strings depending on how the association was defined, for example. :comments instead of "comments" .

+76
Nov 13 '10 at 18:24
source share

For future Googlers in Rails 4 will now respond:

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

Taken from here: stack overflow

EDIT:

reflections , starting with 4.2, now takes strings instead of characters, which are a fun bug to track. If you want to continue using characters, you should switch to reflect_on_association(:assoc_name) . Also note that reflections is actually a public api that will report things like HABTM, even though it all goes through the hood. Rails reflections are actually used in _reflections

+20
Jan 03 '14 at 19:38
source share

For an ActiveRecord object, I use:

 object._reflections 

So, I can manipulate the hash return. For example:

 object._reflections.keys.each do |key| object.public_send(key).destroy_all end 

In the above example, delete all relationships from the database.

-one
Mar 09 '16 at 17:32
source share



All Articles