Ruby On Rails:接收json,解析并保存在数据库中

时间:2014-11-18 21:41:05

标签: ruby-on-rails json ruby-on-rails-4

我想将一个json发布到rails控制器,然后通过单独的控制器将每个json保存到数据库。

为此,我将这个json发布到rails controller:

            jsonList = {
                "table": {column1:"column1",column2:"column2"},
                "record": {name:"record 1"}
            };

并在rails控制器中收到json下面的内容:

Started POST "/api/calculate.json" for 127.0.0.1 at 2014-11-19 00:52:13 +0330
Processing by Api::V1::CalculateController#create as JSON
  Parameters: {"table"=>{"column1"=>"column1", "column2"=>"column2"}, "record"=>{"name"=>"record 1"}, "calculate"=>{"table"=>{"column1"=>"column1", "column2"=>"column2"}, "record"=>{"name"=>"record 1"}}}

但在我做任何事情之前,我在rails服务器日志中遇到错误:

Completed 500 Internal Server Error in 2ms

ActionView::MissingTemplate (Missing template api/v1/calculate/create, api/v1/base/create with {:locale=>[:en], :formats=>[:json], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :jbuilder]}. Searched in:
  * "/Users/mgh/Documents/Maliat/sama/app/views"
):
  actionview (4.1.6) lib/action_view/path_set.rb:46:in `find'
  actionview (4.1.6) lib/action_view/lookup_context.rb:124:in `find'
  actionview (4.1.6) lib/action_view/renderer/abstract_renderer.rb:18:in `find_template'
  actionview (4.1.6) lib/action_view/renderer/template_renderer.rb:41:in `determine_template'

我搜索此错误,但找不到任何有用的指南。

RailsController

class Api::V1::CalculateController < Api::V1::BaseController
  require 'json'
  def create
    ....
  end
end

我有另一个问题。我想通过单独的控制器将每个json保存到数据库。例如,我有一个RecordController并通过以下代码使用create操作:

def create
    temp = Record.new(params[:record])
    temp.save
end

和这种类型:

def create
   temp = Record.create(params[:record])
end

但我在服务器日志中遇到错误

ActiveModel::ForbiddenAttributesError (ActiveModel::ForbiddenAttributesError):
  app/controllers/api/v1/calculate_controller.rb:6:in `create'

RecordController

class Api::V1::RecordController < Api::V1::BaseController
  require 'json'
  def create
    @data = Record.create(record_params)
    @data.save
    respond_with(@data)
  end
  private
  def record_params
    params.require(:record).permit(:name)
  end
end

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

您需要查看Rails中强参数功能的使用。这里也回答了类似的问题:Active Model Forbidden attributes error

答案 1 :(得分:0)

为什么你要分割JSON并发送到两个独立的控制器而不是创建一个控制器方法并解析你的JSON并存储到数据库中,

JSON格式:

{
  "table": {column1:"column1",column2:"column2"},
  "record": {name:"record 1"}
};

控制器方法:

def create_record_and_table
  record = params[:record]
  @record = Record.new(:name => record['name'])
  @record.save

  table = params[:table]
  @table = Table.new(:column1 => table['column1'], :column2 => table['column2'])
  @table.save
end