[英]rails Redirect to action incorrect URL
I have a scenario being: 我有一种情况是:
resources :magazines do
resources :articles do
resources :comments
end
end
So as to avoid nesting more than 2 levels deep I have re-factored this to be: 为了避免嵌套超过2个级别,我将其重构为:
resources :magazines do
resources :articles
end
resources :articles do
resources :comments
end
My article show action URL is: /magazines/3/articles/11 我的文章显示操作URL是:/ magazines / 3 / articles / 11
In this view I have a form for creating a new comment. 在此视图中,我有一个用于创建新评论的表单。
When a comment is saved successfully the form redirects which all works well. 成功保存评论后,表单将重新定向,一切正常。
When the form submission is not successful I wish to redisplay the view with validations errors displayed. 当表单提交不成功时,我希望重新显示视图并显示验证错误。 I understand the correct way to do this is to render the 'articles/show' view.
我了解执行此操作的正确方法是呈现“文章/显示”视图。 This also works and the view is redisplayed with the validation errors shown.
这也可以使用,并重新显示视图并显示验证错误。
The problem is when the save fails and articles/show is rendered the URL is no longer correct and is shown as: /articles/11/comments 问题是当保存失败并且呈现文章/节目时,URL不再正确,并显示为:/ articles / 11 / comments
class ArticlesController < ApplicationController
def show
@article = Article.find(params[:id])
@comments = @article.comments.order(created_at: :asc).page(params[:page]).per_page(5)
@comment = Comment.new
end
end
class CommentsController < ApplicationController
def create
@article = Article.find(params[:id])
@comment = @article.comments.new(discussion_params)
@comment.user_id = current_user.id
if @comment.save
redirect_to @article
else
render 'articles/show'
end
end
private
def discussion_params
params.require(:comment).permit(:content)
end
end
I solved this by changing my routes back to the way it originally was and now the article show action includes the magazine in the url. 我解决了这一问题,方法是将路线改回原来的样子,现在,文章展示操作将网址中包含杂志。
I understand this breaks the "no more than 2 levels deep" routing rule but it's the only way I can get it to work. 我知道这打破了“深度不超过2层”的路由规则,但这是我使其工作的唯一方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.