In _follow.html.slim I am trying to make a link to "Add Friend" with this:
= 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. 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"}
I'm following this tutorial http://francik.name/rails2010/week10.html and he doesn't define a route for this action. 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).
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.