Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get rails associations from console

Tags:

I have a model in my Rails application - User. I want all the associations to be listed in rails console, along with the type of association(1-1, 1-many).

like image 284
shajin Avatar asked May 04 '11 13:05

shajin


People also ask

How do I get rails console?

Go to your browser and open http://localhost:3000, you will see a basic Rails app running. You can also use the alias "s" to start the server: bin/rails s . The server can be run on a different port using the -p option. The default development environment can be changed using -e .

How do you escape the console in Rails?

To exit the console, type: quit .


1 Answers

User.reflect_on_all_associations 

This will return an array of associations similar to this:

#<ActiveRecord::Reflection::AssociationReflection:0x00000105575548 @macro=:has_many, @name=:posts, @options={}, @active_record=User(id: integer, login: string), @collection=false> 

Sample code:

reflections = User.reflect_on_all_associations reflections.each do |reflection|   puts ":#{reflection.macro} => :#{reflection.name}" end 
like image 178
Dylan Markow Avatar answered Sep 23 '22 01:09

Dylan Markow