Skip to content

Instantly share code, notes, and snippets.

@weyus
Created April 2, 2011 20:26
Show Gist options
  • Save weyus/899848 to your computer and use it in GitHub Desktop.
Save weyus/899848 to your computer and use it in GitHub Desktop.
Simple way to default all fields of a table when there are NOT NULL columns that you don't want to set (Rails 2.3.8)
def after_initialize
if new_record?
Mergeinfo.columns.select {|c| (! c.null) && (c.name != Mergeinfo.primary_key)}.each do |c|
default_value = case c.type
when :integer
0
when :string
''
when :boolean
false
end
self.send("#{c.name}=", default_value) unless self.send(c.name) #Make sure not to clobber any initialization parameters
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment