Padrino model from json data

若如初见. 提交于 2019-11-30 21:13:44

问题


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.



来源:https://stackoverflow.com/questions/8386446/padrino-model-from-json-data

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!