website design and development

Weblog - 2 items for ActiveRecord

View all
litespeed hosting Ruby on Rails cpanel smtp plesk port 26 email DNS spam rss IE6 float CSS gmail ActiveRecord has many through plugins news subversion migrations shell webmin mail IE7 ssl Capistrano git Flash Mac OS X ruby gems rspec cucumber Textmate Mac OS X webrat Rails 3 scope

ActiveRecord Has many through and assignment

With Has many through associaitions if you do a simple assignment of an entire collection it does not work.

eg.
2 models Asset and Client have a has_many through relation ship with each other through AssetClient.

The following does not work

@asset.clients = @clients

So a method is needed in Asset like so to make it work.

def clients=(new_clients)
  new_clients.each do |item|
    clients << item unless clients.include?(item)
  end
  clients_to_remove = clients - new_clients
  clients_to_remove.each do |item|
    clients.delete(item)
  end
end

ActiveRecord ruby Script without Rails

23 Sep 2010 ActiveRecord  Ruby on Rails

Below is an example script of how to use existing ActiveRecord Models in a rails app without loading the entire rails app.


#!/usr/bin/env ruby

require 'rubygems'
require 'active_record'
require 'yaml'
 
RAILS_ROOT = File.join(File.expand_path(File.dirname(__FILE__)), '..')
puts RAILS_ROOT
 
dbconfig = YAML::load(File.open("#{RAILS_ROOT}/config/database.yml"))
ActiveRecord::Base.establish_connection(dbconfig["development"])

require "#{RAILS_ROOT}/app/models/site"

Site.all.each do |site|
  puts site.domain
end

© Level Systems 2007