来自JSON数据的Padrino模型 [英] Padrino model from json data

查看:120
本文介绍了来自JSON数据的Padrino模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在为我正在从事的项目寻找Padrino,这似乎非常合适,因为我理想地希望支持以json格式发送和接收的数据.

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?

在Blog示例中,他们简要浏览了一下,但似乎只是将参数数据传递到了Post模型的初始化器中,让我假设它只是神奇地知道如何处理所有事情...不确定这是否是情况,如果是,则使用Padrino功能或ActiveRecord(这就是示例中所使用的功能).

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).

我知道我可以使用ActiveSupport进行基于JSON的编码/解码,但这只是给我一个原始对象,并且由于每个模型的存储问题都位于主模型类中,因此我需要使用mixin或其他方法来实现此目的,这似乎很讨厌.

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?

推荐答案

是的,您可以使用provides,每个响应对象都将调用to_json,即:

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}

您将能够更新帐户模型的记录12.

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

这篇关于来自JSON数据的Padrino模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆