【问题标题】:Determine which page a :delete request is coming from确定 :delete 请求来自哪个页面
【发布时间】:2012-06-01 08:15:37
【问题描述】:

我想知道如何确定 :delete 请求来自哪个页面?例如,我有一个墙贴出现在用户的主页和展示页面上。当用户从主页删除帖子时,我希望用户被重定向到主页,而如果他从他的节目(个人资料)页面删除它,我希望用户被重定向回那里。但问题是,我无法区分它的来源。

我知道在 :delete 请求中,您不能传入隐藏值,因为它不是 :post。我试过检查参数,但结果都是一样的。它们具有相同的 :method、:controller 和 :action 即

{"_method"=>"delete", "authenticity_token"=>"xNsfq27sBrpssTO8sk0aAzzIu8cvnFJEZ30c17Q+BCM=",
"action"=>"destroy", "controller"=>"pub_messages", "id"=>"33"}

在我的销毁操作中,我有:

def destroy
    @pub_message = PubMessage.find_by_id(params[:id])
    @pub_message.destroy
    redirect_to user_path(@pub_message.to_id)
end

但我不想总是重定向回 user_path,而是想重定向到 root_path,但只是无法确定用户何时在主页上发出销毁操作。

我在视图中显示删除选项的地方是...

<% if current_user == feed_item.user or current_user == feed_item.to %>
   <%= link_to "delete", feed_item,     method: :delete,
                                        confirm: "You sure?",
                                        title: feed_item.content %>
<% end %>

我该如何解决这个问题?

【问题讨论】:

    标签: ruby-on-rails request


    【解决方案1】:
    redirect_to request.referer
    

    或者

    redirect_to :back
    

    会将您重定向到上一页。

    【讨论】:

      【解决方案2】:

      您可以redirect_to :back,如here 所述。这会将您从请求中带回到 HTTP_REFERER。

      【讨论】:

        【解决方案3】:

        您可以使用redirect_to :back 来使用Referer。

        如果您担心许多访问者的浏览器没有在请求中填写 Referer 标头,您可以处理 from 参数:

        def destroy
          @pub_message = PubMessage.find_by_id(params[:id])
          @pub_message.destroy
          redirect_to user_path(@pub_message.to_id) and return if params[:from] == "profile"
          redirect_to home_path # no if to fallback
        end
        
        <% if current_user == feed_item.user or current_user == feed_item.to %>
          <%= link_to "delete", feed_path(feed_item, from: "profile"), method: :delete,
                                                                       confirm: "You sure?",
                                                                       title: feed_item.content %>
        <% end %>
        

        【讨论】:

          【解决方案4】:

          可以传入额外的参数:

          <%= link_to "delete", feed_item_path(feed_item, :foo => :bar),
                           method: :delete,
                           confirm: "You sure?",
                           title: feed_item.content %>
          

          然后使用这些来决定你要重定向到哪里。

          如果您不喜欢将这些作为查询参数,那么您可以设置不同的路由来为您传递这些参数。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2012-04-26
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多