0
votes

Here i'm trying to save json data to sqlite database using rails controller, but i'm not getting json data to controller parameters

In a specific controller I have the below list of params:

Parameters: {"person"=>"{\"name\":\"akhil\",\"profession\":\"it\",\"address\":\"hyderabad\",\"mobilenum\":67588}"}

Controller

def createPerson

  puts "parameters are : "+params[:person].to_s
  user_params = ActiveSupport::JSON.decode(params[:person])
  puts "parameters name:"+user_params[:name].to_s
  @person = Person.new(name: user_params[:name], profession: 
  user_params[:profession], address: user_params[:address], mobilenum: 
  user_params[:mobilenum]) 
  @person.save

end  

It is showing below error

(no implicit conversion of nil into String)

I'm getting the nil value in user_params[:name].to_s

Could you please help me to solve this

1
Did you try `params['person']?kunashir

1 Answers

0
votes

Seems like all you need to do is to create a new Person record after submitting a form. Well, probably you would want to use strong params and make a little refactor, so your controller will look something like this:

class PersonsController < ApplicationController
  # you can name your action simply `create`, so you can use resource routing
  def create
    # most probably you don't need to make person an instance variable
    person = Person.new(person_params)
    # and here it is a good practice to check if you really saved your person
    if person.save
      # do something to tell user that the record is saved, e.g.
      flash[:success] = 'person has been saved'
    else
      # show user why your person record is not saved, e.g.
      flash[:error] = "person cannot be saved: #{person.errors.full_messages.to_sentence}"
    end
  end

  private

    # and here is the method for your permissible parameters
    def person_params
      params.require(:person).permit(:name, :profession, :address, :mobilenum)
    end
end