Notes posted by tinogomes
RSS feed
Integrate enum with PostgreSQL Enumerated Types
Extract from:
http://www.sitepoint.com/enumerated-types-with-activerecord-and-postgresql/
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'); SQL add_column :users, :gender, :gender, index: true end def down remove_column :users, :gender execute <<-SQL DROP TYPE gender; SQL end end
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' } end
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.

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 end
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 }

Passing a block with methods
Code example
Google = Struct.new(:address) do def latitude -1 end def longitude -2 end def with_address "with #{address}" end end g = Google.new("Some Addres") puts g.address puts g.latitude puts g.longitude puts g.with_address
Result
# >> Some Addres # >> -1 # >> -2 # >> with Some Addres