Get rails associations from console
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
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
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