Skip to content

Instantly share code, notes, and snippets.

@mixtli
Created April 19, 2011 22:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mixtli/929866 to your computer and use it in GitHub Desktop.
Save mixtli/929866 to your computer and use it in GitHub Desktop.
postgres cti hacks
module ActiveRecord
module ConnectionAdapters
class PostgreSQLAdapter < AbstractAdapter
# For some reason, I have to override these two methods, or record ids don't get updated in
# the object after creating an object.
def prefetch_primary_key?(table_name = nil)
true
end
def next_sequence_value(sequence_name = nil)
query("SELECT nextval('#{sequence_name}')")[0][0]
end
end
end
end
create_table :nodes do |t|
t.string :type
t.string :label
end
create_table :interfaces, :id => false. :options => "INHERITS(nodes)" do |t|
t.string :ip_address
end
create_table :data_sources do |t|
t.integer :node_id
t.string :name
end
class Node <ActiveRecord::Base
has_many :data_sources
end
class Interface < Node
set_table_name "interfaces"
set_sequence_name "nodes_seq_id"
validates :ip_address, :presence => true
end
class DataSource < ActiveRecord::Base
belongs_to :node
end
interface = Interface.create!(:label => 'somelabel', :ip_address => '127.0.0.1')
puts interface.ip_address ---> '127.0.0.1'
puts interface.id ---> 1
# So far so good
node = Node.find(1) ---> #<Interface id: 1, :label => 'somelabel'>
puts node.ip_address ---> ActiveModel::MissingAttributeError: missing attribute: ip_address
# it breaks, but if we reload, it starts working
node.reload
puts node.ip_address ---> '127.0.0.1'
# but even after the reload, if we try to create children through the association, it bombs again
node.data_sources.create!(:name => 'foo') --> ActiveModel::MissingAttributeError: missing attribute: ip_address
# If we do it this way, it works
ds = DataSource.create!(:node => node, :name => 'foo') -> #<DataSource id: 1, name: 'foo', node_id: 1>
puts ds.node.inspect ---> #<Interface id: 1, label:, 'somelabel', ip_address: '127.0.0.1'>
# but if we grab the datasource fresh from the db, it breaks again
ds = DataSource.find(1)
puts ds.node.inspect ---> #<Interface id: 1, :label => 'somelabel'>
puts ds.node.ip_address ---> ActiveModel::MissingAttributeError: missing attribute: ip_address
# reloading doesn't help now. The log shows that the query is "SELECT nodes.* FROM nodes WHERE nodes.id = 1"
ds.node.reload
puts ds.node.ip_address ---> ActiveModel::MissingAttributeError: missing attribute: ip_address
# The only way I seem to be able to get the node with its attributes is to call find again
n = Node.find(ds.node.id)
n.reload
puts n.ip_address = '127.0.0.1'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment