Skip to content

Instantly share code, notes, and snippets.

@copiousfreetime
Created February 5, 2009 04:54
Show Gist options
  • Select an option

  • Save copiousfreetime/58552 to your computer and use it in GitHub Desktop.

Select an option

Save copiousfreetime/58552 to your computer and use it in GitHub Desktop.
# Returns a copy of the attributes hash that only includes those
# attributes that have values.
def attributes_with_values
returning Hash.new do |with_values|
@attributes.each_pair do |name, value|
if value⋅
with_values[name] = value
else
column = column_for_attribute(name)
if column.has_default? and !column.null then
with_values[name] = value
end
end
end
end
end
# Creates a record with values matching those of the instance attributes
# and returns its id.
def create
if self.id.nil? && connection.prefetch_primary_key?(self.class.table_name)
self.id = connection.next_sequence_value(self.class.sequence_name)
end
insertable_attributes = attributes_with_values
quoted_attributes = attributes_with_quotes(true, true, insertable_attributes.keys )
column_names = quoted_column_names( quoted_attributes )
statement = if column_names.empty?
connection.empty_insert_statement(self.class.table_name)
else
"INSERT INTO #{self.class.quoted_table_name} " +
"(#{column_names.join(', ')}) " +
"VALUES(#{quoted_attributes.values.join(', ')})"
end
self.id = connection.insert(statement, "#{self.class.name} Create",
self.class.primary_key, self.id, self.class.sequence_name)
@new_record = false
id
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment