Sunday, March 6, 2016

Code School Pluralsights Your Database is Your Friend Learn-to-Code Database Fundamentals Notes and Tutorial Course Review

This is my notes and review from the Code School Pluralsights database fundamental series "Database is Your Friend"
Your Database is Your Friend (Code School Pluralsights video)
made by pluralsights
Key concepts: database concepts & fundamentals (1. Data Integrity, Concurrency, Reporting), examples in Rails
Time accessed: March 6, 2016 Code School free weekend, covers best practice
Rails is not a prerequisite
Style: pluralsights, not the typical gamified Code School course completed with an opening theme song, challenges,

A lot of a use of rails * migrations * to  modify database * state *

Best practice: the presenter prefers to NOT using rolling changes forward or backward in a PRODUCTION ENVIRONMENT. Instead he uses
$bundle exec rake db:drop db:create db:migrate db:seed
to wipe out and recreate the database from scratchw when changes are needed.

- Data Modeling video agenda: 1. Not Null Constraints, 2. Foreign Keys 3. Duplicate Data 4. Polymorphic association alternative 5. Reactive integrity Checks
- Rails error example NoMethodError in Books#show occurred on line <%= @book.blurb.truncate(100) %> tried to call .truncate() on a text but didn't work. A hot fix, a trick is to convert the nil field, which caused the NoMethodError to be a string so use <%= @book.blurb.to_s.truncate(100) %> But it's a temporary hot fix. We are like to encounter unexpected nil again elsewhere or the same mistake in the future, will cause another bandage fix. If we edit a book, entered nothing in the blurb field upon saving the field will no longer be nil but emtpy string.  Nil versus Empty String not provided versus provided but empty. It's not exposed in the UI and will cause inconsistent, and does-not-make-sense data called Incoherent Data. We need to figure out where the nil comes from (may be an import script that forgot the blurb field).
- an activerecord validation may help such as validate :blurb, presence: true But this will prevent empty string as well, so we add some additional condition validate :blurb, presence: true, if: ->(record) {record.nil?} But some SQL statements and activerecord methods can bypass validations such as false)
- The best way is to fix the database scheme and make sure nil is never stored for that data field using rails generate migration add_not_null_to_blurb First we need to update all data to make valid <code> Book.update_all({blurb:''}, {blurb:nil}) </code> replacing all existing nil with empty string. The next step is to change the column to not allowing nil and set a default value <code>change_column :books, :blurb, :text, null: false, default:''</code>

No comments:

Post a Comment

MATLAB eBook on Machine Learning

Working on graduate study work? MATLAB now offers a free eBook on Machine Learning. Great resource for those in the academia. https://www....