Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create an ActiveRecord Instance from Json

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.

like image 246
Mark Swardstrom Avatar asked May 15 '13 23:05

Mark Swardstrom


1 Answers

You can try to use JSON.parse on your JSON string task_json this way:

task = Task.new(JSON.parse(task_json))
like image 150
Pierre-Olivier Avatar answered Oct 24 '22 16:10

Pierre-Olivier