Padrino model from json data

2019-02-16 03:54发布

问题:

I have been looking at Padrino for a project I am working on, and it seems a great fit, as I would ideally be wanting to support data being sent and received as json.

However I am wondering if there is any automated helper or functionality built in to take data from a post request (or other request) and put that data into the model without having to write custom logic for each model to process the data?

In the Blog example they briefly skim over this but just seem to pass the parameter data into the initilizer of their Post model, making me assume that it just magically knows what to do with everything... Not sure if this is the case, and if so is it Padrino functionality or ActiveRecord (as thats what they seem to use in the example).

I know I can use ActiveSupport for JSON based encoding/decoding but this just gives me a raw object, and as the storage concerns for each model reside within the main model class I would need to use a mixin or something to achieve this, which seems nasty.

Are there any good patterns/functionality around doing this already?

回答1:

Yep, you can use provides and each response object will call to_json i.e:

get :action, :provides => :json do
  @colletion = MyCollection.all
  render @collection # will call @collection.to_json
end

Here an example of an ugly code that fills certain models.

# Gemfile
gem 'json' # note that there are better and faster gems like yajl

# controller
post "/update/:model/:id", :provides => :json do
  if %w(Account Post Category).include?(params[:model])
    klass = params[:model].constantize
    klass.find(params[:id])
    klass.update_attributes(JSON.parse(params[:attributes]))
  end
end

Finally if you POST a request like:

attributes = { :name => "Foo", :category_id => 2 }.to_json
http://localhost:3000/Account/12?attributes=#{attributes}

You'll be able to update record 12 of the Account Model.