How to fix "NoMethodError (undefined method []' for nil:NilClass): app/controllers/..."

SilentCity

I am using rails and I am building a page that creates new "people"(people/new), but without using forms. Using javascript, I scan a page with user inputs and i end up with a javascript object looking like this:

obj = { name: "John", age: 30, city: "New York" };

I then send a post request using javascript to the controller :

fetch('/people', {
    method: 'POST',
    user_params: stringified
})
.then((resp) => resp.json())
.then(function (data) {
    console.log(data)
})
.catch(function (error) {
    console.log(error)
})  

Issue is, the console in the browser is indicating an error 500 :

POST http://localhost:3000/reports 500 (Internal Server Error)
SyntaxError: Unexpected token < in JSON at position 0

Reading the terminal, I get the following error, which i think is the source of the problem :

NoMethodError (undefined method `[]' for nil:NilClass):

app/controllers/people_controller.rb:16:in `create'

Here is my controller :

class PeopleController < ApplicationController
  skip_before_action :verify_authenticity_token , only: [:create]

  def index
    @people = Person.all
  end

  def new
    @person = Person.new
  end

  def create
    Person.create(name: params[:user_params][:name], age: params[:user_params][:age], city: params[:user_params][:city])
  end
end

I have tried changing the syntax in create in the controller :

params[:user_params[:age]]

instead of

params[:user_params][:age]

Which gives me the error

TypeError (no implicit conversion of Symbol into Integer)

I believe however, having looked online for a long time that this change was wrong.

FYI here is what the variable "stringified" looks like when the inputs are empty

{"name":"","age":"","city":""}

I want the information sent (user_params) to be stored in the database.

RichardAE

Unless I'm missing something, your JSON doesn't follow the usual Rails format of having a top level 'user' key, e.g params[:user][:name]. You are creating the object with no top level key, so just do:

Person.create(name: params[:name], age: params[:age], city: params[:city])

Also you can look in the Rails console at what the params object looks like. If it still doesn't work paste your console output.

Edit:

Now it looks like your person is being created from your comments you need to do something afterwards. E.g

def create
   @person = Person.new(name: params[:name], age: params[:age], city: params[:city])

   if @person.save
     redirect_to @person
   else
     render :new
   end
end

That will require you to create a 'show' action for your controller as well and a view to go with it.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related