Automatic counter-cache issue with has-many association in Rails 4.2.x

Recently while working on one of our project there was an requirement of tracking count of records associated with has-many association. But also there was "is_hidden" flag set on some of the records which I do not suppose to count in counter as those were hidden records. So default counter_cache option of rails active-record was not appropriate in this case which automatically counts and caches the number of associated records and keeps cache updated. Refer following model code for this. class Order < ActiveRecord::Base belongs_to :customer, counter_cache: true end class Customer < ActiveRecord:

Preloading associations while using find_by_sql

To preload the associated records we generally use #includes, #preload or #eager_load for more information please see this blog This will work perfectly if we preload associations for an ActiveRecord::Relation, but in case if we want to load associated records for an Array, these methods will fail Let's consider this example class Company < ActiveRecord::Base has_many :users end class User < ActiveRecord::Base belongs_to :company end Say we have a query, which is performing joins and also have sub queries, then we would need to use find_by_sql, to generate the query. But find_

Prepared statements in Rails

Rails 3.1 and above has an awesome feature of prepared_statements. The basic idea behind prepared statements is to compile SQL statements once and cached for it future use. In other words - The benefit to prepared statements is that the database does not have to compile a query plan for every piece of SQL sent to it, potentially saving a lot of time. Checkout an excellent blog(blog) to know more on prepared_statements. Recently, I had to get raw sql from AR object so that I can pass it to EXPLAIN statement to get total number of

Rails 4 has asset digest issues

For those upgrading to OR using Rails 4 Please have a look at the github thread Proposed solution : OR