Rails: select unique values from a column

Model.select(:rating) The result of this is a collection of Model objects. Not plain ratings. And from uniq‘s point of view, they are completely different. You can use this: Model.select(:rating).map(&:rating).uniq or this (most efficient): Model.uniq.pluck(:rating) Rails 5+ Model.distinct.pluck(:rating) Update Apparently, as of rails 5.0.0.1, it works only on “top level” queries, like above. Doesn’t work on … Read more

Rails 3: Get Random Record

Thing.first(:order => “RANDOM()”) # For MySQL :order => “RAND()”, – thanx, @DanSingerman # Rails 3 Thing.order(“RANDOM()”).first or Thing.first(:offset => rand(Thing.count)) # Rails 3 Thing.offset(rand(Thing.count)).first Actually, in Rails 3 all examples will work. But using order RANDOM is quite slow for big tables but more sql-style UPD. You can use the following trick on an indexed … Read more

When to use a “has_many :through” relation in Rails?

Say you have these models: Car Engine Piston A car has_one :engine An engine belongs_to :car An engine has_many :pistons Piston belongs_to :engine A car has_many :pistons, through: :engine Piston has_one :car, through: :engine Essentially you are delegating a model relationship to another model, so instead of having to call car.engine.pistons, you can just do … Read more

ActiveRecord, has_many :through, and Polymorphic Associations

There is a known issue with Rails 3.1.1 that breaks this functionality. If you are having this problem first try upgrading, it’s been fixed in 3.1.2 You’re so close. The problem is you’re misusing the :source option. :source should points to the polymorphic belongs_to relationship. Then all you need to do is specify :source_type for … Read more

Rails order by results count of has_many association

Rails 5+ Support for left outer joins was introduced in Rails 5 so you can use an outer join instead of using counter_cache to do this. This way you’ll still keep the records that have 0 relationships: Company .left_joins(:jobs) .group(:id) .order(‘COUNT(jobs.id) DESC’) .limit(10) The SQL equivalent of the query is this (got by calling .to_sql … Read more

ActiveRecord OR query Hash notation

There are 5 options that could be considered as implementations of «Hash notation» (the last two are kinda hash-ish): With Ruby on Rails 5 you are able to do the following chaining using ActiveRecord::Relation#or method: Person.where(name: ‘Neil’).or(Person.where(age: 27)) Use where_values together with reduce. The unscoped method is necessary only for Rails 4.1+ to ensure default_scope … Read more