Hi, I'm using sequel with sinatra to make a json conversation with a javascript application. I'm using json_serialize plugin to.
I learned that set_fields is my friend allowing me to restrict the fields that comes from js world that I want to apply to my model's instance. When I say SomeModel.select([:field1, :field2]).all.to_json the resulting json objects will containg a property called json_object that maps to 'SomeModel'. That property is used when the object is deserialized, in order to instantiate the right ruby type. When I get back I use put to update some value I need to: data = JSON.parse(request.body.read) instance.set_fields(data.values, [:field1, :field2]) Since the data that come from client has json_class property it'll deserialize to SomeModel, and since set_fields needs a Hash, I need to pass data.values. The docs clearly states that It needs a hash, but you can be fooled if you pass SomeModel instance : instance.set_fields(data, [:field1, :field2]) It works! If you pass options it'll force you to use a hash like : instance.set_fields(data, [:field1, :field2], :missing => :skip) It's because the it'll hit the set_fields implementation that needs hash methods. When the data comes from the client in a http post with a new record, it usually does not come with json_class property. This time you need to remember that you already have a Hash. It would be nice if set_fields were more forgiving with this. Kind of hash = hash.values if hash < Sequel::Model I'm using the awesome to_json(:only => [:field1, :field2]) in cases like at insertion where I have a full instance on the server, but just want to return the fields the client needs to access. I've looked the from_json (plugin) code and it's merely calls set. def from_json(json) set(JSON.parse(json)) end It would be nice if it used set_fields making it more secure like to_json with :only parameters, this way I could call : instance.from_json(data, [:field1, :field2]) and I would have all functionality packed in a call. Off course these json translation wouldn't be needed if I had used form submission instead of json objects. What do you think ? Thanks in advance and sorry the english. Geraldo Lopes de Souza -- You received this message because you are subscribed to the Google Groups "sequel-talk" group. To post to this group, send email to [email protected]. To unsubscribe from this group, send email to [email protected]. For more options, visit this group at http://groups.google.com/group/sequel-talk?hl=en.
