2

在 _follow.html.slim 我试图用这个链接到“添加朋友”:

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

我希望它在保持在同一页面上的同时调用关系控制器中的方法 req 。它目前甚至没有调用该方法并返回此错误:No route matches {: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

结尾

4

1 回答 1

5

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).

For that, you can simply do, in your config/routes.rb file:

get 'relationships/req'

Now, your req action has a path, relationships_req_path (responding to HTTP GET requests).

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). This file allows use to dynamically add/modify content on the current page.

于 2013-10-05T22:50:23.887 回答