【问题标题】:How to check which page a form was submitted on in Rails?如何在 Rails 中检查表单提交到哪个页面?
【发布时间】:2015-12-10 11:25:37
【问题描述】:

我在与其他模型的多个关联中使用 cmets 模型。关系始终是相同的:评论“属于”另一个模型的项目,而那些其他模型“有很多”cmets。

我正在其他模特的展示页面上呈现评论表单,如下所示:

<%= render "comments/form" %>

当用户单击提交按钮时,我希望他被重定向到不同的页面,具体取决于他之前所在的页面。当我搜索解决方案时,我通过 APIdock 找到了 current_page? ActionView 助手(参见 http://apidock.com/rails/v4.2.1/ActionView/Helpers/UrlHelper/current_page%3F),并认为在 cmets 控制器中使用它是个好主意:

respond_to do |format|
  if (@comment.save) && (current_page?(controller: 'game', action: 'show'))
    format.html { redirect_to game_comments_url, notice: 'Comment was successfully created.' }
    format.json { render :show, status: :created, location: @comment }
  elsif (@comment.save) && (current_page?(controller: 'comment'))
    format.html { redirect_to @comment, notice: 'Comment was successfully created.' }
    format.json { render :show, status: :created, location: @comment }
  else
    format.html { render :new }
    format.json { render json: @comment.errors, status: :unprocessable_entity }
  end
end

但遗憾的是,我收到以下错误消息:

undefined method `current_page?' for #<CommentsController:0x007f67fe42e1a0>

如果有人能给我一个解决方案,告诉我如何找出特定表单是在哪个页面上提交的,或者至少是如何将用户重定向到不同页面的方法,我将不胜感激。

【问题讨论】:

    标签: ruby-on-rails forms


    【解决方案1】:

    current_page? 是视图助手,因此在控制器中不可用。

    您可以在控制器中通过request.referrer 获取参考网址

    【讨论】:

    • 感谢您的提示。如何调试该方法向我显示的结果?我将代码更改为:if (@comment.save) &amp;&amp; (URI(request.referer).path == '/games'),但是当我尝试它时,它使用“else”分支代替,因为结果不适合。
    • 您可以尝试在控制器中添加puts URI(request.referer).path,然后在终端中查看确切路径
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-10
    • 1970-01-01
    相关资源
    最近更新 更多