【问题标题】:Rails sends GET request when it should be POSTRails 在应该是 POST 时发送 GET 请求
【发布时间】:2014-03-02 03:37:10
【问题描述】:

我有一个应该发送 POST 请求的 Rails 应用程序,但由于某种原因正在发送 GET。

查看:

<% if @competition.users.exclude?(@user)  %>
  <%= link_to 'Attend Competition', attend_competition_path(@competition.id), :method => :post %>
<% else %>
  <%= link_to 'Withdraw', withdraw_competition_path(@competition.id), :method => :post %>
<% end %>

控制器:

def attend
  p current_user.daily
  @competition = Competition.find(params[:id])
  if @competition.users.include?(current_user)
    flash[:error] = "You're already attending this competition."
  elsif current_user.daily == []
    flash[:error] = "You must have a working device to compete."
  else
    current_user.competitions << @competition
    flash[:success] = "Attending competition!"
  end
  redirect_to @competition
end

def withdraw
  p "WITHDRAWING"
  @competition    = Competition.find(params[:id])
  p @competition
  attendee = Attendee.find_by_user_id_and_competition_id(current_user.id, @competition.id)
  if attendee.blank?
    flash[:error] = "No current attendees"
  else
    attendee.delete
    flash[:success] = 'You are no longer attending this competition.'
  end
  p attendee
  redirect_to @competition
end

路线:

resources   :competitions do
  post 'attend', on: :member
end

resources :competitions do
  member do 
    post 'withdraw'
  end
end

所以我单击按钮并转到页面,但收到一个错误,即没有 GET 请求的路由。不应该有 get 请求的路由,但应该是发送帖子。

ActionController::RoutingError (No route matches [GET] "/competitions/1/withdraw")

【问题讨论】:

  • 您的浏览器是否禁用了javascript?
  • 来自 rails 的 link_to 文档:Note that if the user has JavaScript disabled, the request will fall back to using GET
  • 我需要启用哪些 javascript?我有 Jquery,但我需要 Jquery-ujs 还是 Jquery-ui

标签: ruby-on-rails ruby-on-rails-3


【解决方案1】:

你可以做的一件事是运行:

 rake routes

这将显示您所有可用的路线及其方法。我相信,由于您正在向其他方法发布帖子,然后创建它不了解您要做什么。我正在寻找是否可以找到正确的方法来执行此操作,但我确实发现 Rails 文档说:

如果您依赖 POST 行为,您应该在控制器的操作中使用请求对象的 post?、delete?、:patch 或 put? 方法来检查它。

因此,您可能需要检查控制器操作中的帖子。我寻找了如何执行此操作的示例,但找不到任何内容。

查看您的路线,它应该按照您的方式工作。要尝试的另一件事是使用“put”而不是“post”。

您可能要考虑的另一个选项是将其设置为表单并将按钮设置为链接的样式(如果您想要的外观)。

迈克·莱利

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-18
    • 2018-10-29
    • 2015-06-10
    • 1970-01-01
    • 2018-09-04
    • 1970-01-01
    相关资源
    最近更新 更多