finding invalid foreign keys in Rails

Sometimes it would be useful to tell users of your Ruby on Rails application if there is a problem in the database, such as some foreign keys are invalid. As an example, let's assume you have two models, Book and Author, such that each Book has an author_id which connects with Author via its primary key, id. That is, the tables are: books(id, author_id) and authors(id). Each table probably has fields other than that, but those are the only fields we need to worry about. Below is a method that generates an unordered HTML list for display to the users:

Ruby

class Book < ActiveRecord::Base
  # Returns HTML about which rows have invalid foreign keys
  def self.find_bad_foreigners
    msg = ''

    find( :all ).each do |book|
      unless Author.exists?( book.author_id )
        author_id = ( book.author_id || 'NULL' ).to_s
        msg << '<li>Book with ID ' << book.id.to_s + ' has a non-existent
          author ID: ' << author_id + '</li>'
      end
    end
   
    if msg.blank?
      nil
    else
      '<ul class="error">' << msg + '</ul>'
    end
  end
end

You could have similar methods in your Rails models. Maybe on the main page of your application, the above method could be displayed. If there are no invalid foreign keys, nothing will show up. Otherwise, the user will see a list of the invalid keys that need fixing.

This entry was posted in Daily life and tagged , , , by Sarah. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>