我想问邮递员的param帖子,所以我可以在rails中的控制器中获取它。
这是我的控制器
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
当我在邮递员中尝试时,我的用户名,名字,姓氏和年龄都是空的。
我像这样发布
[
{
"username": "admin2",
"firstname": "Reza Adha",
"lastname": "Hamonangan",
"age": 23,
}
]
当我尝试发布
时,我的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)
我认为我在控制器中做错了从邮递员处获取POST数据。 请帮我.. 谢谢你的关注。
答案 0 :(得分:1)
你需要在params上使用user
键:
[
"user": {
"username": "admin2",
"firstname": "Reza Adha",
"lastname": "Hamonangan",
"age": 23,
}
]
允许user
使用强大的参数:
params(:user).permit(:username, :firstname, :lastname, :age)
答案 1 :(得分:0)
好的,所以我从here找到答案。我在邮递员T_T中插错了
它看起来应该是这样的
{
"user" : {
"username": "admin2",
"firstname": "Reza Adha",
"lastname": "Hamonangan",
"age": 23
}
}
并且我没有给出头文件aplication / json。 我很抱歉这个大惊小怪。谢谢@ user100693和@MurifoX