在Rails DB中保存二维数组的问题

时间:2017-10-13 13:48:10

标签: ruby-on-rails ruby

我有一个二维数组,其中包含来自用户运行日志的lat和lng数据。数组中可以包含许多元素。 例如:

    rundata = [[40.7174141, -74.0015233], [40.7174141, -54.0015233], 
    [20.7174141, -74.0015233]]

我需要将其保存到数据库中。这是我的控制器在强大的参数下的样子:

    class TrackrunsController < ApiController
       before_action :require_login, except: [:index, :show]

     def create
        trackrun = Trackrun.create!(trackruns_params)
        trackrun.user = current_user    
        if trackrun.save
            render json: {
              message: 'ok',
              trackrun: trackrun,
          }
        else
          render json: {message: 'Could not create run'}
     end

      private
      def trackruns_params
         params.require(:trackrun).permit(:rundata)
      end

  end

我的跟踪运行模型:

  class Trackrun < ApplicationRecord
    belongs_to :user, optional: true
    serialize :rundata

  end

在我的控制台中为未经授权的参数保持错误。

任何想法都可能出错。

错误:

    Processing by TrackrunsController#create as HTML
    09:34:03 api.1  |   Parameters: {"trackrun"=>{"rundata"=>
    [[40.7174141, -74.0015233]]}}
    09:34:03 api.1  |   User Load (0.7ms)  SELECT  "users".* FROM 
    "users" WHERE "users"."auth_token" = $1 LIMIT $2  [["auth_token", 
    "2H8CzejjWK2SD3KhfZDgq6tc"], ["LIMIT", 1]]
    09:34:03 api.1  | Unpermitted parameter: :rundata
    09:34:03 api.1  |    (0.2ms)  BEGIN
    09:34:03 api.1  |   SQL (0.8ms)  INSERT INTO "trackruns" 
    ("created_at", "updated_at") VALUES ($1, $2) RETURNING "id"  
    [["created_at", "2017-10-13 13:34:03.072208"], ["updated_at", 
    "2017-10-13 13:34:03.072208"]]
    09:34:03 api.1  |    (1.2ms)  COMMIT
    09:34:03 api.1  |   User Load (0.3ms)  SELECT  "users".* FROM 
    "users" WHERE "users"."auth_token" = $1 LIMIT $2  [["auth_token", 
    "2H8CzejjWK2SD3KhfZDgq6tc"], ["LIMIT", 1]]
    09:34:03 api.1  |    (0.2ms)  BEGIN
    09:34:03 api.1  |   SQL (0.7ms)  UPDATE "trackruns" SET 
    "updated_at" = $1, "user_id" = $2 WHERE "trackruns"."id" = $3  
    [["updated_at", "2017-10-13 13:34:03.084035"], ["user_id", 1], 
    ["id", 27]]
    09:34:03 api.1  |    (1.2ms)  COMMIT
    09:34:03 api.1  | Completed 200 OK in 58ms (Views: 0.6ms | 
    ActiveRecord: 13.2ms)

更新:

这是来自前端的请求......

handleStopRun () {
const entireRun = [...this.state.runData]
console.log('from stop run', entireRun)
navigator.geolocation.clearWatch(this.state.runID);
this.setState({ runID: null }) 
axios('/trackruns', {
  method: 'POST',
  headers: {
    'Authorization': `Token ${Auth.getToken()}`,
    token: Auth.getToken(),
  },
  data: {
    trackrun: {
      // rundata is the two dimensional array being passed to rails
      rundata: this.state.runData,
    }
  },
}).then(res => {
  console.log(res)
  this.setState({
    shouldFireRedirect: true,
  });
}).catch(err => {
  console.log(err);
});

}

另一个更新:进行了下面列出的一些更改。现在又出现了另一个错误

控制器:

def create
    trackrun = Trackrun.new
    trackrun.rundata = trackruns_params
    trackrun.user = current_user
    trackrun.save
    render json: { trackrun: trackrun }
end

private
def trackruns_params
    a = params.require(:trackrun).permit(:rundata=>[])
    a
end

MODEL:

class Trackrun < ApplicationRecord

   belongs_to :user, optional: true
   serialize :rundata, Array

end

错误:从昨天开始调试,没有运气,请帮忙!

 Started POST "/trackruns" for 127.0.0.1 at 2017-10-14 10:56:18 -0400
 10:56:18 api.1  | Processing by TrackrunsController#create as HTML
 10:56:18 api.1  |   Parameters: {"trackrun"=>{"rundata"=>[[40.7174796, 
    -74.0013829]]}}
 10:56:18 api.1  |   User Load (1.8ms)  SELECT  "users".* FROM "users" 
  WHERE "users"."auth_token" = $1 LIMIT $2  [["auth_token", 
 "RKs5Z8h21aYanGTmGgxMnDry"], ["LIMIT", 1]]
 10:56:18 api.1  | Unpermitted parameter: :rundata
 10:56:18 api.1  | Completed 500 Internal Server Error in 5ms 
 (ActiveRecord: 1.8ms)
 10:56:18 api.1  |
 10:56:18 api.1  |
 10:56:18 api.1  |
 10:56:18 api.1  | ActiveRecord::SerializationTypeMismatch (can't 
 serialize 
`rundata`: was supposed to be a Array, but was a 
ActionController::Parameters. -- <ActionController::Parameters {} 
permitted: true>):
10:56:18 api.1  |
10:56:18 api.1  | app/controllers/trackruns_controller.rb:12:in 
`create'

2 个答案:

答案 0 :(得分:0)

我认为问题在于批量作业。请尝试以下方法:

trackrun = Trackrun.new
trackrun.rundata = variable_with_the_array
trackrun.user = current_user  
if trackrun.save 
....  

编辑和评论后编辑: 灰,添加

contentType: 'application/json' 

到你的json请求。对于发布到TrackrunsController的请求也使用

contentType: 'application/json' 

data: JSON.stringify(data). 

答案 1 :(得分:0)

当您将数组列入白名单时,您必须明确指定它是一个数组。

  def trackruns_params
     params.require(:trackrun).permit(rundata: [])
  end