Weblog - 2 items for ActiveRecord
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
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
