Latest Tweet
- Dropped container of polynesian sauce on floor, fully-open side down. NOTHING CAME OUT. Chick-fil-A, champion of viscous sauces. 2 days ago
- More updates...
Categories
Tags
academia alcohol animals boyfriend cooking databases email forwards family Flickr food friends health Javascript Lexington Linux list Mario math movies music news OS X Perl PHP politics programming quizzes Rails rants reading Ruby screenshots shopping Sims sports themes tutorials Twilight is ridiculous vehicles video games videos weather Web development work zombies again-
Recent Comments
-
Random Quote
Is not all life pathetic and futile? ...We reach. We grasp. And what is left in our hands at the end? A shadow. Or worse than a shadow
— misery. - "The Complete Sherlock Holmes," Sir Arthur Conan Doyle Syndication
All posts RSS feed
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
# 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.