Type a keyword and hit enter to start searching. Press Esc to cancel.

Posts Tagged ‘database’

The perfect database schema is one where you don’t need to concede form to any obscure requirements. In that perfect scenario all associated models could be individually identified with a single foreign key.   According to the Rails guides, you can only define an association’s foreign key with a single column. We live in an imperfect world with many obscure business requirements, so sometimes we need to use two keys.  One common scenario is when you need to centralize and synchronize data from multiple outside API’s.  Luckily, there is a solution. This example will be based on an Entity Attribute […]

ActiveRecord is awesome! However, it’s not without a few downsides and common pitfalls. The simplicity sometimes comes at a cost of efficiency. A great example is the n+1 problem when scoping an ActiveRecord relation by a belongs_to association. For example, take the following associated Models class Employee < ActiveRecord::Base belongs_to :company end class Company < ActiveRecord::Base has_many :employees has_many :offices end If you were using an Employee instance method to find company offices for the Employee, you may do something like this: Office.where(company: self.company) Or you could say: Office.where(company_id: self.company_id) Both examples will give you the following query: SELECT * FROM offices […]

Rails uniqueness validations are not thread safe!  This is a problem when even single threaded Rails servers are susceptible to race conditions.  Luckily, this is an easy problem to avoid. If you have a multi-threaded Rails server like Puma or Passenger Enterprise, use asynchronous background processing with tools like Sidekiq, or have a load balanced environment with multiple web servers then the race condition is real!  Just defining a uniqueness validation will not keep your data unique and can cause a lot of headaches. First, let’s look at why they are not thread safe with a simple example.  Take the […]