What is the best way to create a new Ruby/Rails object without triggering any database actions?
For example if I have a Task class
class Task < ActiveRecord::Base
  has_many :tags
  has_one :location
end
And I want to create one from cached data that looks something like this
task_json = { 
  id: 1, 
  title: 'My Task', 
  tags: [ 
    { title: 'Tag1' }, 
    { title: 'Tag2'} 
  ]
  location: { lat: 46.0, lon: -120.1 } 
} 
And I want to reconstitute the object, but not trigger any database interactions.
@task = Task.new
@task.id = task_json['id']
@task.title = task_json['title']
@task.location = Location.new(:lat => task_json['location']['lat'], :lon => task_json['location']['lon'])
@task.tags = ...
Ideally, there would be no chance of saves or database interaction in any way once the object is built.
You can try to use JSON.parse on your JSON string task_json this way:
task = Task.new(JSON.parse(task_json))
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With