ruby-on-rails – Rails 3:“:method =>:post”不起作用……当它’POST’时似乎是’GET’

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – Rails 3:“:method =>:post”不起作用……当它’POST’时似乎是’GET’前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正试图在我的Rails 3应用程序中实现“友谊”,如 Railscast 163:Self Referential Assosication所述

我按照描述设置了所有内容.我正在使用一个基本的用户模型登录Authlogic工作正常.但是,当我尝试使用以下链接添加朋友时:

<% for user in @users %>   
 <%=h user.username %> 
  <%= link_to "Add Friend",friendships_path(:friend_id => user),:method => :post %>     
<% end %>

我得到一个重定向到http:// localhost:3000 / friendships?friend_id = 2和一个未知的操作无法找到FriendshipsController错误的动作’index’,没有进一步的解释.这是特别奇怪的,因为我有一个硬编码重定向回到我当前用户的“User#show”方法(即在添加好友重定向配置文件).

如果它有帮助,这是我的“友谊#create”方法

def create  
  @friendship = current_user.friendships.build(:friend_id => params[:friend_id])  
  if @friendship.save  
    flash[:notice] = "Added friend."  
    redirect_to :controller => 'users',:action => 'show',:id =>'current_user'
  else  
    flash[:notice] = "Unable to add friend."  
    redirect_to :controller => 'users',:id =>'current_user' 
  end  
end

知道是什么原因引起的吗?我发现有人在这里有类似的问题,但我找不到明确的解决办法:Rails 3 and Friendship Models

在此先感谢您的帮助!

〜丹

解决方法

@H_403_21@ 我认为link_to将参数放入查询字符串中,因为它是用html链接创建的,即使你输入:method => :如果js被禁用则发布.

你可以用javascript:onclik事件来模拟帖子.

aniway,使用link_to方法:post通常是一个坏主意.
在rails中你可以使用button_to helper来实现这个pourpose,并将其设置为链接.

编辑:
在Rails3 doc中,似乎link_to在使用params调用时必须模拟button_to的相同行为:method =>:post

(dynamically create an HTML form and
immediately submit the form ).

但即使启用了javascript,在Rails 3.0.3中对我来说也不是这样.
我会调查.

无论如何,你应该使用按钮和表格来做任何非GET的事情;超链接故意不允许GET以外的方法

EDIT2:好,rails3不会创建内联表单来通过链接模拟发布请求.在Rails3中,data-method = post属性添加标记中,以通过javascript函数对其进行操作.这样,如果禁用了js,请求会在get调用中优雅地降级.

原文链接:https://www.f2er.com/ruby/267500.html

猜你在找的Ruby相关文章