« Return to Thread: Get a list of all foreign keys (with their respective tables

Re: Get a list of all foreign keys (with their respective tables

by Adam Akhtar-2 :: Rate this Message:

Reply to Author | View in Thread


Roy Pardee wrote:
> Ach, of course.  Thanks Fred.

I actually ended up not going via the classes, but just dealing with the
database direct:

def index_all_tables_foreign_keys
  sql = ActiveRecord::Base.connection
  tables = sql.select_values("show tables")
  messages = []
  tables.each do |table|
    foreign_key_column_hashes = sql.select_all("desc
#{table}").select{|hash| hash["Field"].match(/_id$/)}
    foreign_key_column_hashes.each do |column_hash|
      begin
        if column_hash["Key"] == ""
          sql.execute("alter table #{table} add index
(#{column_hash["Field"]})")
          messages << "added index to #{table}:#{column_hash["Field"]}"
        end
      rescue
        messages << "FAILED to add index to
#{table}:#{column_hash["Field"]}"
      end
    end
  end
  messages
end

I invite (genuinely, without sarcasm) the ruby/rails gurus to rip it to
shreds.  Is this a sensible approach?
--
Posted via http://www.ruby-forum.com/.

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@...
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@...
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---

 « Return to Thread: Get a list of all foreign keys (with their respective tables