2014-03-02 45 views
0

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

查看:

<% 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请求的路由。不应该有获取请求的路由,但应该发送帖子。

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

您的浏览器中禁用JavaScript脚本吗? – usha

+0

从rails文档link_to:'请注意,如果用户禁用JavaScript,请求将回退到使用GET' – usha

+0

我需要启用什么JavaScript?我有Jquery,但是我需要Jquery-ujs还是Jquery-ui – Marcus

回答

0

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

rake routes 

会告诉你所有可用的路线和他们的方法。我相信,既然你正在做一个方法的文章,然后创建它不理解你正在尝试做什么。我想看看我是否能找到合适的方法来做到这一点,但我确实发现了Rails的文件说:

如果你是依靠职务行为,你应该在你的控制器的动作检查它通过使用请求对象的方法进行post?,delete?,:patch或put ?.

因此,您可能需要检查控制器操作中的帖子。我寻找一个如何做到这一点的例子,但找不到任何东西。在你的路由

来看,它应该工作,你有它的方式。另一个要尝试的是使用“put”而不是“post”。

,你可能要考虑另外一个选择是让一个形式和风格一样,如果这是你要的样子链接按钮。

Mike Riley

相关问题