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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
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.