Skip to content

Instantly share code, notes, and snippets.

@jgaskins
Created March 28, 2014 01:19
Show Gist options
  • Save jgaskins/9823026 to your computer and use it in GitHub Desktop.
Save jgaskins/9823026 to your computer and use it in GitHub Desktop.
ActiveRecord default attributes
require 'active_record'
require 'pg'
ActiveRecord::Base.establish_connection host: 'localhost',
database: 'jamie',
adapter: 'postgresql'
class ARModel < ActiveRecord::Base
def initialize(attributes={})
# AR::Base#create w/o args passes nil because lol.
attributes ||= {}
# Override defaults with passed-in args
super(default_attributes.merge(attributes))
end
private
def default_attributes
{ name: 'foo' }
end
end
p ARModel.new
# => #<ARModel name: "foo">
p ARModel.new(name: 'bar')
# => #<ARModel name: "bar">
p ARModel.create
# => #<ARModel name: "foo">
p ARModel.create(name: 'baz')
# => #<ARModel name: "baz">
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment