在这个场景中有来自注释的post_id,但是我想从post资源中获得只具有id的后缀,所以注释中的post_id和id来自post是相同的id,所以我尝试将两者关联起来
def set_post
@post = Post.find(params[:id])
end
def set_comment_post
@post = Post.find_by(post_id: set_post)
end日志显示了错误。
拜托,有人会在这件事上给小费吗?


class PostsController < ApplicationController
before_action :set_comment_post only: [:comments]
before_action :set_post, only: [:show, :update, :destroy], except: [:comments]
before_action :set_user, only: [:show, :update, :destroy, :new]
# GET /posts
# GET /posts.json
def comments
@comments = @post.comments.order('created_at desc')
render json: @comments
end
# POST /posts
# POST /posts.json
def create
@post = current_user.posts.build(post_params)
if @post.save
render json: "Posted successfully", status: 201
else
render json: @post.errors, status: :unprocessable_entity
end
end
# PATCH/PUT /posts/1
# PATCH/PUT /posts/1.json
def update
if @post.update(post_params)
render json: "Posted updated successfully", status: 200
else
render json: @post.errors, status: :unprocessable_entity
end
end
private
def set_user
@current_user = User.find_by(params[:id])
end
# Use callbacks to share common setup or constraints between actions.
def set_post
@post = Post.find(params[:id])
end
def set_comment_post
@post = Post.find_by(:post_id => set_post)
end
# Never trust parameters from the scary internet, only allow the white list through.
def post_params
params.require(:post).permit(:title, :body, :user_id, :posts_count)
end
end请求传递的参数
"/posts/" + this.props.match.params.post_id + "/comments",发布于 2018-10-26 01:32:23
还不清楚为什么你需要两个方法来做同样的事情,但我认为你想要的是
仅在多个端点需要before_action时才使用它。另外,不要同时使用[:only]和[:except]这两种方法。这应该是可行的:
class PostsController < ApplicationController
before_action :set_post, only: [:show, :update, :destroy, :comments]
before_action :set_user, only: [:show, :update, :destroy, :new]
def comments
@comments = @post.comments.order('created_at desc')
render json: @comments
end
def create
@post = current_user.posts.build(post_params)
if @post.save
render json: "Posted successfully", status: 201
else
render json: @post.errors, status: :unprocessable_entity
end
end
def update
if @post.update(post_params)
render json: "Posted updated successfully", status: 200
else
render json: @post.errors, status: :unprocessable_entity
end
end
private
def set_user
@current_user = User.find_by(params[:id])
end
def set_post
@post = Post.find(params[:id])
end
def post_params
# add comments attributes if our text field is called 'text'
params.require(:post).permit(:title, :body, :user_id, :posts_count, comments_attributes: [ :id, :text ] )
end
end您还可能需要设置accepts_nested_attributes_for
class Post
accepts_nested_attributes_for :comments, allow_destroy: true
has_many :comments, dependent: :destroy
end然而,您要在前端传递数据,您需要传递带有嵌套字段的post表单,以便进行注释。请参阅helpers.html#nested-forms
https://stackoverflow.com/questions/52999893
复制相似问题