[英]Postman problems in post request
我正在尝试将 postman 与 mi controller “评论”的发布请求一起使用。 此请求向我显示以下错误:
“NoMethodError(未定义的方法‘新闻’......”
这是评论 model:
class Comment < ApplicationRecord
include Discard::Model
belongs_to :user, optional: true
belongs_to :news, optional: true
validates :news_id, presence: true
validates :user_id, presence: true
validates :body, presence: true
end
这是 controller:
module Api
module V1
class CommentsController < ApplicationController
before_action :authenticate_request, only: %i[index create update destroy]
before_action :set_comment, only: %i[update destroy]
before_action :authorize_user, only: %i[show create update destroy]
def index
@comment = Comment.order('created_at DESC')
render json: CommentSerializer.new(@comment,
fields: { comment: :body })
.serializable_hash, status: :ok
end
def create
@comment = Comment.new(comment_params)
@comment.user = @current_user
@comment.news = @current_user.news.find(params[:news_id])
if @comment.save
render json: CommentsSerializer.new(@comment).serializable_hash, status: :created
else
render_error
end
end
def update
if ownership?
@comment = Comment.update(comment_params)
render json: CommentSerializer.new(@comment).serializable_hash
else
render json: @comment.errors, status: :unprocessable_entity
end
end
def destroy
if ownership?
@comment.discard
head :no_content
else
render json: { error: 'unauthorized' }, status: :unauthorized
end
end
private
def set_comment
@comment = Comment.find(params[:id])
end
def comment_params
params.require(:comment).permit(:body)
end
def render_error
render json: { errors: @comment.errors.full_messages },
status: :unprocessable_entity
end
def render_unauthorized
render status: :unauthorized, json: {
errors: [I18n.t('errors.controllers.unauthorized')]
}
end
end
end
end
当我在 postman 中发送帖子请求时,它显示以下问题:NoMethodError(#<User id: 27, first_name: "rafa", last_name: "quinteros", email: "rafa4@email. com”,password_digest:[过滤],照片:nil,role_id:1,created_at:“2022-08-05 13:42:51.360055000 -0300”,updated_at:“2022-08-05 13:42:51.360055000 -0300” ,discarded_at:无>):
好吧,您的comment.user
收到@current_user
,但用户没有新闻方法/关系。 您应该编写一个新闻方法来阻止此错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.