Padrino model from json data

℡╲_俬逩灬. 提交于 2019-12-01 01:59:35

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.

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