activerecord snippets

How to use named_scope in Rails

Tagged ruby, activerecord, named_scope, rails  Languages ruby

Simple example of how to use the named_scope feature:

class Feed < ActiveRecord::Base
 
  named_scope :active, :conditions => "(active = 1)"
  named_scope :stale,  :conditions => ["last_updated > ?", 30.minutes.ago.to_s(:db)]

Usage:

Feed.active # return the active feeds

Chaining is also possible:

Feed.active.stale # return the feeds that need to be updated

How to backup ActiveRecord model data to YAML with ar_fixtures

Tagged fixtures, backup, activerecord, rails, yaml  Languages ruby

First install the plugin:

script/plugin install http://github.com/mileszs/ar_fixtures/commits/master

Then dump data for all models with:

rake db:data:dump:all

There's a task for loading the data into the database, see rake -T for more information.

You can also do this without a plugin by using ActiveSupport::JSON and File.write to seed your database.

How to run ActiveRecord migrations from the console

Tagged console, migrations, schema, activerecord  Languages ruby

There are multiple ways of running migrations from the console. This might be the easiest one to remember:

irb ActiveRecord::Schema
add_index :followers, [:leader_id, :follower_id], :unique => true

You can also paste the migration code into the console window:

class ModifyRating < ActiveRecord::Migration
  def self.up
    change_column :products, :rating, :decimal, :precision => 5, :scale => 3
  end

  def self.down
  end
end

Run the migration by typing ModifyRating.up.

How to customize to_json

Tagged to_json, activerecord, rails  Languages ruby
def to_json(options = {})
  if options.empty?
    super :only => [:id, :name]
  else
    super options
  end
end

Now post.to_json will only include the id and name attributes.

Note that for arrays of objects--at least with Rails 2.3.4--you need use the same parameters on the array.to_json method:

Post.all.to_json :only => [:id, :name]

Rails find_or_initialize and find_or_create methods are deprecated

Tagged activerecord, rails, find_or_create, find_or_initialize  Languages ruby

The find_or_initialize and find_or_create methods have been deprecated in Rails x.x.x. This is what you need to do:

Before:
User.find_or_create_by_name('XXX')

After:
User.where(name: 'XXX').first_or_create
User.where(name: 'XXX').first_or_create!

Before:
User.find_or_initialize_by_name('XXX')

After:
User.where(name: 'XXX').first_or_initialize

If you want the old methods, see https://github.com/rails/activerecord-deprecated_finders.

Also see http://apidock.com/rails/ActiveRecord/Relation/first_or_create

Puma, Sinatra, ActiveRecord and "could not obtain a database connection"

Tagged puma, activerecord, sinatra  Languages ruby

Getting connection errors with Puma, Sinatra and ActiveRecord?

ActiveRecord::ConnectionTimeoutError at /
could not obtain a database connection within 5.000 seconds (waited 5.002 seconds)

Add this to your Sinatra application:

use ActiveRecord::ConnectionAdapters::ConnectionManagement

Frozen ActiveRecord Attributes Validator

Tagged frozen, attribute, activerecord  Languages ruby

Disallows update of frozen attributes:

#
# Validates that an attribute cannot be changed after object has been created.
#
# Usage:
#   validates :user_id, :token, frozen_attribute: true, allow_blank: true
#
# allow_blank: set to true to allow setting nil attributes
#
class FrozenAttributeValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    changed = record.send("#{attribute}_changed?")
    was_not_blank = if options[:allow_blank]
                      !(record.send("#{attribute}_was").blank? && value.present?)
                    else
                      true
                    end
    if record.persisted? && changed && was_not_blank
      record.errors.add(attribute, 'is frozen')
    end
    true
  end
end

Put the thing in app/validators/frozen_attribute_validator.rb. Use it like this:

class Horse < ActiveRecord::Base
  validates :user_id, :token, frozen_attribute: true, allow_blank: true

How to use ActiveRecord without Rails

Tagged ruby, rails, standalone, activerecord  Languages ruby

This is an example of how to use ActiveRecord without Rails.

Short version

require 'active_record'
require 'pg' # postgresql

ActiveRecord::Base.establish_connection(
  adapter: "postgresql",
  encoding: "unicode",
  database: "matrix",
  username: "postgres",
  password: ""
)

class User < ActiveRecord::Base
end

Long version

app.rb:

require 'active_record'
require 'sqlite3'
require 'logger'

ActiveRecord::Base.logger = Logger.new('debug.log')
configuration = YAML::load(IO.read('config/database.yml'))
ActiveRecord::Base.establish_connection(configuration['development'])

class User < ActiveRecord::Base
end

db/migrate/001_schema.rb

class Schema < ActiveRecord::Migration
  def change
    create_table :users, force: true do |t|
      t.string :name
    end
  end
end

Rakefile:

require_relative 'app'

task :default => :migrate

desc "Run migrations"
task :migrate do
  ActiveRecord::Migrator.migrate('db/migrate', ENV["VERSION"] ? ENV["VERSION"].to_i : nil)
end

database.yml:

development:
  adapter: sqlite3
  database: db/data.sqlite3
  pool: 5
  timeout: 5000