Tuesday, December 18, 2012

[Rails] ActiveRecord object from json

Hi All

I'm trying to create an ActiveRecord object 'directly' from some JSON data.  By 'directly' - I mean without 'walking' the parsed JSON data, but rather just passing the parsed JSON data to a method that will process all the data.

To keep the question simple - let's say I have two objects.  A Survey and a Question.   Each Survey can have many Questions.

Here's a script containing the json data and my attempt at creating an ActiveRecord object directly from the json string ...

# begin test.rb script

json = '{

 "name":"Fundraising Survey",

 "description":"A survey about a fundraiser",

 "questions":[

  {"text":"How clearly did our organization explain our fundraising goals?"},

  {"text":"Was the cost of attending our fundraiser too high, too low, or about right?"}

 ]

}'

survey = Survey.new

survey.attributes = ActiveSupport::JSON.decode(json)

# end test.rb script


For reference = here is the ruby code for the Survey and Question classes ...

class Survey < ActiveRecord::Base

 has_many :questions, :dependent => :destroy

 accepts_nested_attributes_for :questions, :allow_destroy => true,

                               :reject_if => lambda {|attrs| attrs['text'].blank? }

 attr_accessible :name, :description

end


class Question < ActiveRecord::Base

 belongs_to :survey

 acts_as_list :scope => :survey

 validates_presence_of :text, :message => 'Text can not be blank'

 attr_accessible :survey_id, :text

end


I get this error when I run the test.rb script (see code snippet above) ...

/Users/dse/.rvm/gems/ruby-1.9.3-p327@sq/gems/activerecord-3.2.9/lib/active_record/associations/association.rb:204:in `raise_on_type_mismatch': Question(#70357035179920) expected, got Hash(#70357017137920) (ActiveRecord::AssociationTypeMismatch)


Any help would be greatly appreciated.


Thanks again

Dave


--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msg/rubyonrails-talk/-/ngpKVHYpMVoJ.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate