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

Converting camel case to underscore case in ruby

Rails’ ActiveSupport adds underscore to the String using the following: class String def underscore self.gsub(/::/, “https://stackoverflow.com/”). gsub(/([A-Z]+)([A-Z][a-z])/,’\1_\2′). gsub(/([a-z\d])([A-Z])/,’\1_\2′). tr(“-“, “_”). downcase end end Then you can do fun stuff: “CamelCase”.underscore => “camel_case”

Fully custom validation error message with Rails

Now, the accepted way to set the humanized names and custom error messages is to use locales. # config/locales/en.yml en: activerecord: attributes: user: email: “E-mail address” errors: models: user: attributes: email: blank: “is required” Now the humanized name and the presence validation message for the “email” attribute have been changed. Validation messages can be set … Read more

Rails: Default sort order for a rails model?

default_scope This works for Rails 4+: class Book < ActiveRecord::Base default_scope { order(created_at: :desc) } end For Rails 2.3, 3, you need this instead: default_scope order(‘created_at DESC’) For Rails 2.x: default_scope :order => ‘created_at DESC’ Where created_at is the field you want the default sorting to be done on. Note: ASC is the code to … Read more

SSL Error When installing rubygems, Unable to pull data from ‘https://rubygems.org/

For RVM & OSX users Make sure you use latest rvm: rvm get stable Then you can do two things: Update certificates: rvm osx-ssl-certs update all Update rubygems: rvm rubygems latest For non RVM users Find path for certificate: cert_file=$(ruby -ropenssl -e ‘puts OpenSSL::X509::DEFAULT_CERT_FILE’) Generate certificate: security find-certificate -a -p /Library/Keychains/System.keychain > “$cert_file” security find-certificate … Read more