0

I have a two dimensional array that contains lat and lng data from a user's run log. Array can contain numerous elements in it. For example:

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

I need to save this to the db. Here is what my controller looks like with strong params:

    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

My Model for trackrun:

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

  end

Keep getting an error for Unpremiited params in my console.

Any ideas what might be wrong.

error:

    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)

UPDATE:

this is the request from the frontend...

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);
});

}

ANOTHER UPDATE: Made some changes that are listed below. Getting another error now

Controller:

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

ERROR: Tring to debugg since yesterday with no luck, Please help!

 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'
4
  • I see Unpermitted parameter: :rundata in your log. Probably you should change permit for rundata. Check this one: stackoverflow.com/questions/15983208/… Commented Oct 13, 2017 at 14:31
  • Tried that as well. Changed my params to params.require(:trackrun).permit({:rundata => []}) Error still remains to unpermitted params Commented Oct 13, 2017 at 14:41
  • I don't believe you. params.require(:trackrun).permit(rundata: []) should work. Commented Oct 13, 2017 at 14:49
  • 1
    params.require(:trackrun).permit(rundata: []) still gets an unpermitted params error Commented Oct 13, 2017 at 14:59

2 Answers 2

0

I think the issue is with the bulk assignment. Try the following:

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

Edit after question edit and comment: Ash, add

contentType: 'application/json' 

to your json request. For requests that post to TrackrunsController use also

contentType: 'application/json' 

and

data: JSON.stringify(data). 
Sign up to request clarification or add additional context in comments.

12 Comments

gives this error: NameError (undefined local variable or method `variable_with_the_array' for #<TrackrunsController:0x007fe4e9957a38>):
variable_with_the_array is meant to be a placeholder that you should change to whatever the variable holds the array you are trying to save. (ex. rundata)
this is the error now: ActiveRecord::StatementInvalid (PG::InvalidTextRepresentation: ERROR: malformed array literal: "--- []
so this works in the rail console and it saves the data: Trackrun.create!({:rundata => [[2323,2323], [232, 4545]]}) . i think the problem is definitely in my strong params
What variable and what does contain when you pass when you get PG::InvalidTextRepresentation: ERROR: malformed array literal:? Calling create and then save should be consolidated, otherwise 'could not create the run' is more a 'user could not be associated to the run'
|
0

When you whitelist an array, you have to explicity specify it's an array.

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

1 Comment

This doesn't work since run_data is the multidimensional array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.