Rails: crea un openstruct a partir de json enviado a través de ajax

I have this json object (which i don't really know what is inside) and I want to store it into a rails model with an openstruct attribute

so for example with jquery I send this json to the good url:

    myJSONData =  {"OpenStructObject":{"content":' + Data + '}}
      type: "POST",
      url: 'http://localhost:3000/surveys/',
      dataType: 'json',
      data: myJSONData,
      success: alert('wow : success !')

So how should be written this Survey model ? Maybe something like this :

class Survey < ActiveRecord::Base
  serialize :content, OpenStruct

  def initialize(idunno)
    @content = watever;

I really don't know except that It must be possible to do it !

preguntado el 02 de febrero de 12 a las 10:02

1 Respuestas

Why do you need this to be converted into OpenStruct and save as yaml in db. Instead JSON converted to hash saved as yaml does the same thing without overhead of open struct.


you already have solution in your code. look at this

class Survey < ActiveRecord::Base
  serialize :content, Hash


Here you are serializing content. right!! So it automatically converts assigned hash to yaml before saving. So here is some assignment

survey = Survey.new({:content => {:first => "any hash"}})

Now when you access it back again

#=> {:first => "any hash"}

just simple as it is. You don't have to worry about yaml conversion and back, Rails will take care of it.


Respondido 02 Feb 12, 19:02

yes you've got a point but how to query my yaml file, howto make it belongs to one profil for example ? - Timoun

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.