【发布时间】:2017-04-12 00:13:23
【问题描述】:
我目前正在处理我的项目,但遇到了一些挑战。我有一个项目模型,其中嵌套了评论对象我可以创建一个新评论,但是当我尝试编辑与项目对象关联的评论时,我在浏览器中收到这个奇怪的错误,表明我正在尝试编辑评论属于一个不存在的项目。实际上,当我检查 url 时,项目的 id 并不存在。例如,如果我想编辑属于 id 为 1 的项目的评论,错误消息表明我想编辑属于 id 为 2 的项目的评论。我已经尝试了所有我知道的但不能没有找到问题的根源。 这就是我的评论控制器的样子
[8:04] 类 CommentsController
def index
@projects = Project.all
if params[:project_id]
@comments = @project.comments.all
redirect_to @comments
end
end
def new
if params[:project_id]
@project = Project.find(params[:project_id])
@comment = @project.comments.build
end
end
def create
if params[:project_id]
@project = Project.find(params[:project_id])
@comment = @project.comments.create(comment_params)
if @comment.save
redirect_to @comment
else
render "new"
end
end
end
def show
if params[:project_id]
@project = Project.find_by(:id => params[:id])
@comment = @project.comments.find_by(:id => params[:id])
end
end
def edit
if params[:project_id]
@comment = @project.comments.find_by(:id => params[:id])
end
end
def update
if params[:project_id]
@comment = @project.comments.find_by(:id => params[:id])
@comment.update(comment_params)
redirect_to @comment
render "edit", notice: "You cannot update the comment"
end
end
def destroy
@comment = @project.comments.find_by(:id => params[:id])
@comment.destroy
flash[:notice] = "Comment has been successfully deleted"
redirect_to @project
end
private
def find_project
@project = Project.find_by(id: params[:project_id])
end
def comment_params
params.require(:comment).permit(:content, :project_id)
end
end
【问题讨论】:
标签: ruby-on-rails-5 nested-forms