ActiveRecord.find(array_of_ids), preserving order

Oddly, no one has suggested something like this: index = Something.find(array_of_ids).group_by(&:id) array_of_ids.map { |i| index[i].first } As efficient as it gets besides letting SQL backend do it. Edit: To improve on my own answer, you can also do it like this: Something.find(array_of_ids).index_by(&:id).slice(*array_of_ids).values #index_by and #slice are pretty handy additions in ActiveSupport for arrays and hashes … Read more

ActiveRecord Query Union

Here’s a quick little module I wrote that allows you to UNION multiple scopes. It also returns the results as an instance of ActiveRecord::Relation. module ActiveRecord::UnionScope def self.included(base) base.send :extend, ClassMethods end module ClassMethods def union_scope(*scopes) id_column = “#{table_name}.id” sub_query = scopes.map { |s| s.select(id_column).to_sql }.join(” UNION “) where “#{id_column} IN (#{sub_query})” end end end … Read more

accepts_nested_attributes_for with find_or_create?

When you define a hook for autosave associations, the normal code path is skipped and your method is called instead. Thus, you can do this: class Post < ActiveRecord::Base belongs_to :author, :autosave => true accepts_nested_attributes_for :author # If you need to validate the associated record, you can add a method like this: # validate_associated_record_for_author def … Read more

Eager load polymorphic

My guess is that your models look like this: class User < ActiveRecord::Base has_many :reviews end class Review < ActiveRecord::Base belongs_to :user belongs_to :reviewable, polymorphic: true end class Shop < ActiveRecord::Base has_many :reviews, as: :reviewable end You are unable to do that query for several reasons. ActiveRecord is unable to build the join without additional … Read more

Is there a way to get a collection of all the Models in your Rails app?

The whole answer for Rails 3, 4 and 5 is: If cache_classes is off (by default it’s off in development, but on in production): Rails.application.eager_load! Then: ActiveRecord::Base.descendants This makes sure all models in your application, regardless of where they are, are loaded, and any gems you are using which provide models are also loaded. This … Read more