简体   繁体   English

调用自定义操作,而无需使用Rails link_to重新渲染页面

[英]Calling custom action without re-rendering page with Rails link_to

In _follow.html.slim I am trying to make a link to "Add Friend" with this: 在_follow.html.slim中,我尝试使用以下方式链接到“添加朋友”:

= link_to "Add Friend",  :controller => "relationships", :action => "req"

I want it to call the method req in the relationships controller while staying on the same page. 我希望它在同一个页面上时在关系控制器中调用方法req。 It currently isn't even calling the method and is returning this error: No route matches {:controller=>"relationships", :action=>"req", :name=>"Nathan Glass", :age=>"21"} 当前它甚至没有调用该方法,并返回此错误:没有路由匹配{:controller =>“ relationships”,:action =>“ req”,:name =>“ Nathan Glass”,:age =>“ 21 “}

I'm following this tutorial http://francik.name/rails2010/week10.html and he doesn't define a route for this action. 我正在按照本教程http://francik.name/rails2010/week10.html进行操作 ,他没有为此操作定义路线。 If this error is correct I guess my confusion is why I need a route for this. 如果这个错误是正确的,我想我的困惑就是为什么我需要一个解决方案。 Otherwise, what is my problem here? 否则,我的问题是什么? Thanks! 谢谢!

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

end 结束

First, you always need to define a route for an action. 首先,您始终需要为操作定义一条路线。 If you don't, rails doesn't know that your action exists (even if you specify the controller and the action names in your link_to). 如果不这样做,Rails不会知道您的动作存在(即使您在link_to中指定了控制器和动作名称)。

For that, you can simply do, in your config/routes.rb file: 为此,您只需在config / routes.rb文件中执行以下操作:

get 'relationships/req'

Now, your req action has a path, relationships_req_path (responding to HTTP GET requests). 现在,您的req操作具有一个路径Relationships_req_path(响应HTTP GET请求)。

Then, if you want to call a controller action while staying on the same page, you can do: 然后,如果要在停留在同一页面上的同时调用控制器操作,则可以执行以下操作:

link_to "Add as friend", relationships_req_path, remote: true

The remote: true modifies the link behavior(it will works like an ajax call) and renders the relationships/req.js.erb file by default (which can contain nothing). remote: true修改链接行为(它将像ajax调用一样工作)并默认情况下呈现Relationships / req.js.erb文件(不包含任何内容)。 This file allows use to dynamically add/modify content on the current page. 此文件可用于动态添加/修改当前页面上的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM