tho*_*nch 6 ruby-on-rails ruby-on-rails-3
我正在尝试在我的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 %>
Run Code Online (Sandbox Code Playgroud)
我得到一个重定向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', :action => 'show', :id =>'current_user'
end
end
Run Code Online (Sandbox Code Playgroud)
知道是什么原因引起的吗?我发现有人在这里有类似的问题,但我找不到一个明确的解决方案:Rails 3和友谊模型
在此先感谢您的帮助!
〜丹
and*_*rea 10
我认为link_to将参数放入查询字符串中,因为它是用html链接创建的,即使你输入:method =>:post如果js被禁用.
你可以用javascript:onclik事件来模拟帖子.
aniway,使用link_to方法:post通常是一个坏主意.在rails中你可以使用button_to helper来实现这个pourpose,并将其设置为链接.
编辑:
在Rails3 doc中,似乎link_to在使用params调用时必须模拟button_to的相同行为:method =>:post
(动态创建HTML表单并立即提交表单).
但即使启用了javascript,在Rails 3.0.3中对我来说也不是这样.我会调查.
无论如何,你应该使用按钮和表格来做任何非GET的事情; 超链接故意不允许GET以外的方法
edit2:好的,rails3不会创建内联表单来通过链接模拟发布请求.在Rails3中,data-method = post属性被添加到标记中,以通过javascript函数对其进行操作.这样,如果禁用了js,请求会在get调用中优雅地降级.
这是一个迟到的答案,但它是这个问题的解决方案(至少它适用于我):
<%= link_to "Add Friend", {:controller => :friendships, :action => :create, :friend_id => user_id }, :method => :post %>
Run Code Online (Sandbox Code Playgroud)
我知道你的问题早就应该了,但它可能对某人有帮助:)
| 归档时间: |
|
| 查看次数: |
8450 次 |
| 最近记录: |