Notes posted by tinogomes

RSS feed
August 21, 2016
1 thank

Integrate enum with PostgreSQL Enumerated Types

Extract from:


There are 2 things that we need to do before we can use ActiveRecord::Enum with PostgreSQL Enumerated Types: database migration and enum declaration.

First, let’s create the database migration:

$ bundle exec rails generate migration AddGenderToUsers gender:gender

Next, edit the generated migration to add the type:

# db/migrate/20150619131527_add_gender_to_users.rb
class AddGenderToUsers < ActiveRecord::Migration
  def up
    execute <<-SQL
      CREATE TYPE gender AS ENUM ('male', 'female', 'not_sure', 'prefer_not_to_disclose');

    add_column :users, :gender, :gender, index: true

  def down
    remove_column :users, :gender

    execute <<-SQL
      DROP TYPE gender;

Once you’re finished with that, run the migration:

$ bundle exec rake db:migrate

Now, we have completed the database migration. The next step is to declare an enum in the User model. Earlier, we used both the Array and Hash forms to declare an enum. For the integration to work, we need to declare an enum using the Hash form:

# app/models/user.rb
class User < ActiveRecord::Base
  enum gender: {
    male:                   'male',
    female:                 'female',
    not_sure:               'not_sure',
    prefer_not_to_disclose: 'prefer_not_to_disclose'

Finally, we can store ActiveRecord::Enum values using PostgreSQL Enumerated Types. As a bonus, all helper methods provided by ActiveRecord::Enum still work as expected.

March 26, 2012 - (v2.3.2 - v3.1.0)
1 thank

Use exist scopes on default_scope - pay attention

To use exists scopes on default_scope , you can use something like:

class Article < ActiveRecord::Base
  scope :active, proc {
    where("expires_at IS NULL or expires_at > '#{Time.now}'")

  scope :by_newest, order("created_at DESC")

  default_scope by_newest

But, if you would add a filter, and it require a lazy evaluate, use block on default_scope declaration, like:

default_scope { active.by_newest }
January 28, 2011 - (>= v1_8_7_72)
1 thank

Passing a block with methods

Code example

Google = Struct.new(:address) do
  def latitude

  def longitude

  def with_address
    "with #{address}"

g = Google.new("Some Addres")

puts g.address
puts g.latitude
puts g.longitude
puts g.with_address


# >> Some Addres
# >> -1
# >> -2
# >> with Some Addres