Created
December 17, 2011 17:09
-
-
Save neovintage/1490769 to your computer and use it in GitHub Desktop.
Using Allocate to Create ActiveRecord Objects
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
j = Job.allocate | |
j.init_with('attributes' => {'name' => 'Awesome Shop', 'title' => 'Test Job', 'status' => 'complete'}) | |
j.title # => 'Test Job' |
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
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') |
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
def find_by_sql(sql) | |
connection.select_all(sanitize_sql(sql), "#{name} Load").collect! { |record| instantiate(record) } | |
end |
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
def instantiate(record) | |
model = find_sti_class(record[inheritance_column]).allocate | |
model.init_with('attributes' => record) | |
model | |
end |
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
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