Created
March 28, 2014 01:19
-
-
Save jgaskins/9823026 to your computer and use it in GitHub Desktop.
ActiveRecord default attributes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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