[英]How to get data from Postman in Rails Controller?
i want to ask about param post from postman so i can get it in controller in rails. 我想问一下邮递员的参数发布,这样我就可以在控制器中找到它了。
here is my controller 这是我的控制器
class Api::V1::UsersController < ApplicationController
before_action :get_user, only: [:show, :fullname]
#get all user object
def index
render :json => User.all
end
# get user object with id
def show
render :json => @user
end
# get full name of user object with id
def fullname
@hasil = @user.firstname + ' ' + @user.lastname
render :json => @hasil
end
# post object into model
def create
@user = User.new(user_params)
@user.save
if @user.save
render :json => @user
else
render :json => @user.errors.full_messages
end
end
private
def user_params
params.permit(:username, :firstname, :lastname, :age)
end
def get_user
@user = User.find(params[:id])
end
end
when i try it in postman, i got null on username, firstname, lastname, and age. 当我在邮递员中尝试时,我得到的用户名,名字,姓氏和年龄为空。
I post it like this 我这样张贴
[
{
"username": "admin2",
"firstname": "Reza Adha",
"lastname": "Hamonangan",
"age": 23,
}
]
My rails server log when i try to post 我尝试发布时我的Rails服务器日志
Started POST "/api/v1/users" for ::1 at 2016-11-18 18:04:24 +0700
ActiveRecord::SchemaMigration Load (0.0ms) SELECT `schema_migrations`.* FROM `schema_migrations`
Processing by Api::V1::UsersController#create as */*
(0.0ms) BEGIN
SQL (1.0ms) INSERT INTO `users` (`created_at`, `updated_at`) VALUES ('2016-11-18 11:04:25', '2016-11-18 11:04:25')
(4.2ms) COMMIT
(0.0ms) BEGIN
(0.0ms) COMMIT
Completed 200 OK in 22ms (Views: 0.3ms | ActiveRecord: 7.2ms)
I think i did something wrong in my controller to get POST DATA from postman. 我想我在控制器中做错了从邮递员那里获取POST数据。 Please help me.. Thank you for your attention.
请帮助我。。谢谢您的关注。
You need the user
key on the params: 您需要在参数上使用
user
密钥:
[
"user": {
"username": "admin2",
"firstname": "Reza Adha",
"lastname": "Hamonangan",
"age": 23,
}
]
And permit the user
on strong params: 并允许
user
使用强大的参数:
params(:user).permit(:username, :firstname, :lastname, :age)
Ok so i found an answer from here .I inserted so wrong in the postman T_T 好的,所以我从这里找到了答案。我在邮递员T_T中插入了错误
it should look like this 它应该看起来像这样
{
"user" : {
"username": "admin2",
"firstname": "Reza Adha",
"lastname": "Hamonangan",
"age": 23
}
}
and i didnt give the header aplication/json. 而且我没有给标头aplication / json。 I am sorry about this fuss.
我为此感到抱歉。 thank you @user100693 and @MurifoX
谢谢@ user100693和@MurifoX
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.