nat*_*ft1 2 routes custom-action ruby-on-rails link-to
在_follow.html.slim中,我正在尝试使用以下链接添加"添加好友":
= link_to "Add Friend", :controller => "relationships", :action => "req"
Run Code Online (Sandbox Code Playgroud)
我希望它在关系控制器中调用方法req,同时保持在同一页面上.它目前甚至没有调用该方法并返回此错误:没有路由匹配{:controller =>"relationships",:action =>"req",:name =>"Nathan Glass",:age =>"21 "}
我正在关注本教程http://francik.name/rails2010/week10.html,他没有为此操作定义路线.如果这个错误是正确的,我想我的困惑是为什么我需要一个这样的路线.否则,我的问题在这里?谢谢!
class RelationshipsController < ApplicationController
def req
puts "req called"*10
# is setting @current_user since the current_user method already returns @current_user?
@current_user = current_user
@friend = User.find_by_name(params[:name])
unless @friend.nil?
if Relationship.request(@current_user, @friend)
flash[:notice] = "Friendship with #{@friend.name} requested"
else
flash[:error] = "Friendship with #{@friend.name} cannot be requested"
end
end
# render somewhere
end
Run Code Online (Sandbox Code Playgroud)
结束
首先,您始终需要为操作定义路线.如果不这样做,rails不知道您的操作是否存在(即使您在link_to中指定了控制器和操作名称).
为此,您可以在config/routes.rb文件中执行以下操作:
get 'relationships/req'
Run Code Online (Sandbox Code Playgroud)
现在,您的req操作有一个路径relationships_req_path(响应HTTP GET请求).
然后,如果要在停留在同一页面上时调用控制器操作,则可以执行以下操作:
link_to "Add as friend", relationships_req_path, remote: true
Run Code Online (Sandbox Code Playgroud)
该remote: true修改的链接行为(它会像一个Ajax调用的作品),并呈现由默认的关系/ req.js.erb文件(可以包含任何内容).此文件允许用于在当前页面上动态添加/修改内容.
| 归档时间: |
|
| 查看次数: |
2743 次 |
| 最近记录: |