[英]i'm trying to pass json data to rails controller using post method in rest client
Here i'm trying to save json data to sqlite database using rails controller, but i'm not getting json data to controller parameters 在这里,我正在尝试使用Rails控制器将json数据保存到sqlite数据库,但是我没有将json数据保存到控制器参数中
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) (不将nil隐式转换为String)
I'm getting the nil value in user_params[:name].to_s 我在user_params [:name] .to_s中得到nil值
Could you please help me to solve this 你能帮我解决这个问题吗
Seems like all you need to do is to create a new Person
record after submitting a form. 似乎您需要做的就是提交表单后创建新的“ Person
记录。 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.