24

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

shajin
  • 3,214
  • 5
  • 38
  • 53

5 Answers5

46
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
Dylan Markow
  • 123,080
  • 26
  • 284
  • 201
  • 1
    Just to clarify, it does not work on an instance of a model. It works on the model class. I actually want all the details from associated records, not the schema level. – Darren Weber Nov 09 '16 at 19:24
  • Agree, We could use reflections = User.reflect_on_all_associations reflections.map(&:name) – mrjusepelo Oct 29 '21 at 21:54
5

Using the gem pry-rails you will be able to access the model, its columns and relationships. Include it in your Gemfile, then you run bundle. You can use the command show-models when you are in your pry console. and you will get the information about all your models.

You can also run show-model (Model_Name) to get information about a specific model

Temitope
  • 51
  • 1
  • 1
2

Add this some where is under /lib. For example clone_deep.rb.

module CloneDeep
  def clone_deep
    kopy = clone
    self.class.reflect_on_all_associations.each do |association|
      next if association.macro == :belongs_to
      cloned_object = case association.macro
                        when :has_many
                          self.send(association.name).collect { |item| item.clone_deep }
                        when :has_one
                          self.send(association.name) && self.send(association.name).clone_deep
                        else
                          clone
                      end
      kopy.send("#{association.name}=", cloned_object)
    end
    return kopy
  end
end

Create new initializer under config/initializers/ folder. Inside this file paste

ActiveRecord::Base.send(:include, CloneDeep)

Now you be able to clone model with all it's has_one and hos_many associations.

cloned_person = person.clone_deep
cloned_person.save
Andrey Yasinishyn
  • 1,851
  • 2
  • 23
  • 36
0

Because I'm a new user, I am unable to clarify/reply to other's posts. I'll note that you need to reload the rails console before checking any changes in associations.

ezis
  • 311
  • 2
  • 10
0

You can do this for any particular :- user = User.reflect_on_association(:user_profile) and user.macro

deepak
  • 198
  • 2
  • 5