Skip to content

Instantly share code, notes, and snippets.

@neovintage
Created December 17, 2011 17:09
Show Gist options
  • Save neovintage/1490769 to your computer and use it in GitHub Desktop.
Save neovintage/1490769 to your computer and use it in GitHub Desktop.
Using Allocate to Create ActiveRecord Objects
j = Job.allocate
j.init_with('attributes' => {'name' => 'Awesome Shop', 'title' => 'Test Job', 'status' => 'complete'})
j.title # => 'Test Job'
class Shop < ActiveRecord::Base
has_many :jobs
end
class Job < ActiveRecord::Base
belongs_to :shop
end
# Example query
Job.find_by_sql('SELECT shops.name, jobs.title, jobs.status FROM shops, jobs WHERE shops.id = jobs.shop_id')
def find_by_sql(sql)
connection.select_all(sanitize_sql(sql), "#{name} Load").collect! { |record| instantiate(record) }
end
def instantiate(record)
model = find_sti_class(record[inheritance_column]).allocate
model.init_with('attributes' => record)
model
end
x = Job.allocate
x.instance_variable_set(:@attributes, {'name' => 'Awesome Shop', 'title' => 'Test Job', 'status' => 'complete'})
x.instance_variable_set(:@attributes_cache, {})
x.instance_variable_set(:@new_record, false)
x.instance_variable_set(:@readonly, false)
x.instance_variable_set(:@destroyed, false)
x.instance_variable_set(:@marked_for_destruction, false)
x.instance_variable_set(:@previously_changed, {})
x.instance_variable_set(:@changed_attributes, {})
x.send(:_run_find_callbacks)
x.send(:_run_initialize_callbacks)
x.title # => 'Test Job'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment