I am creating a users controller to show the users profile page but i am getting this error
ActionController::UrlGenerationError in Users#show
No route matches {:action=>"show", :controller=>"users", :id=>nil}
missing required keys: [:id] error
I am trying to add a profile page for each user so when the user for example goes to
www.mysite.com/users/jack
it will show their profile page
Here's my code:
layouts/_navbar.html.erb
<nav class="navbar navbar-default">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="/">Skillbook</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
</ul>
<ul class="nav navbar-nav navbar-right">
<% if user_signed_in? %>
<td><%= link_to "Profile", user_path(current_user.username) %></td>
<td><%= gravatar_tag current_user.email, size: 20 %><%= current_user.username %></td>
<li><%= link_to "Edit user", edit_user_registration_path %></li>
<li><%= link_to "Log out", destroy_user_session_path ,method: :delete %></li>
<%else%>
<li><%= link_to "Log in", new_user_session_path %></li>
<li><%= link_to " Sign up", new_user_registration_path%></li>
<%end%>
</ul>
</ul>
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>
users_controller.rb
class UsersController < ApplicationController
before_action :set_user, only: [:show]
private
def set_user
#user = User.find_by(username: params[:id])
end
end
routes.rb
Rails.application.routes.draw do
get 'pages/home'
devise_for :users
root 'pages#home'
resources :users, only: [:show, :index]
end
Well, this error simply is what it is:
missing required keys: [:id]
Where, according to your setup, is the username of the currently signed-in user.
In a nutshell, what this is telling you is that you are trying to pass in the username of the signed-in user, but for this instance, the user that is signed in has no username.
To fix this, make sure that the username of the signed-in user, (and all other users for that matter) is not nil
In url you should pass an id of the user, and you do not do that.
What you really want to incorporate is friendly_id gem.
With it set up you will be able to actually present users id as name(or whatever other attribute/combination of attributes you want):
www.mysite.com/users/1
will become
www.mysite.com/users/jack
In your routes file add
get '/users/:id', to: 'users#show', as: '/users/:username'
The last part as: is where you are naming your route. This would give the user with username 'jack' the route /users/jack. Likewise if you wanted to get rid of users altogether you could put as: '/:username'
No need to install another gem.
Justin
Related
I defined a new method in my controller to show customized show page for my houses after one click on search results.
houses_controller.rb
def show_house_search
#house = House.find(params[:id])
#photos = #house.photos
end
then I declared the routes in routes.rb
get '/show_house_search/:id', to: 'houses#show_house_search', as:'show_house_search'
and when I am using it as
<%= link_to show_house_search_path(house.id),id:'house_search' do %>
<li id="house-<%= house.id %>">
<span class="user" style="font-size: 15px;font-weight: 200;text-decoration: dotted;"><%= house.title %></span>
<span class="content"style="font-size: 15px;color: purple;font-weight: 600;">Price <i class="fa fa-inr"></i><%= house.price %></span>
<span class="badge"><%= house.house_structure%></span> </span>
<span class="badge"><%= house.location%></span> </span>
</li>
<%end%>
clicking on this link is showing me this error:
Routing Error
No route matches [GET] "/show_house_search.38"
while I also searched for a route for my request using rails routes
show_house_search_path GET /show_house_search/:id(.:format) houses#show_house_search
try below code:
<%= link_to show_house_search_path(id: house.id) ,id:'house_search' do %>
Please change menthod
show_house_search_path(house.id)
to
show_house_search_path(id: house.id).
As shown in routes.rb, path is /show_house_search/:id(.:format), it seems that id is considered as :format hence appending to routes as( .id).
I am following the railstutorial and now got into the point where header will change dynamically depending on whether the user is logged in or not, using a conditional dropdown as shown below
<header class="navbar navbar-fixed-top navbar-inverse">
<div class="container">
<%= link_to "sample app", root_path, id: "logo" %>
<nav>
<ul class="nav navbar-nav navbar-right">
<li><%= link_to "Home", root_path %></li>
<li><%= link_to "Help", help_path %></li>
<% if logged_in? %>
<li><%= link_to "Users", '#' %></li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
Account <b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li><%= link_to "Profile", current_user %></li>
<li><%= link_to "Settings", '#' %></li>
<li class="divider"></li>
<li>
<%= link_to "Log out", logout_path, method: "delete" %>
</li>
</ul>
</li>
<% else %>
<li><%= link_to "Log in", login_path %></li>
<% end %>
</ul>
</nav>
And here is the logged_in? method defined in the helper
module SessionsHelper
# Logs in the given user.
def log_in(user)
session[:user_id] = user.id
end
# Returns the current logged-in user (if any).
def current_user
#current_user ||= User.find_by(id: session[:user_id])
end
# Returns true if the user is logged in, false otherwise.
def logged_in?
!current_user.nil?
end
end
For some reason this is not working, although I have copied the tutorial exactly. I am not sure if the line (if_logged_in?) is not being called or it is called but returns false. The else block gets executed by the way
I was wondering if there is anyway I can check if the method defined in the helper (logged_in?) is working and gets called correctly? Something like printing an output from the method itself?
A quick way to check whether that method's being called, and what's happening in it, is to throw a debug statement in there, like so:
def logged_in?
Rails.logger.debug("\n\n *** logged_in? #{current_user}")
!current_user.nil?
end
You load the page and then look at your development log and see if that line is there, and whether the user exists.
For more details about debugging, see http://guides.rubyonrails.org/debugging_rails_applications.html.
Hope that helps.
I have an application under development in Rails 3.2.13 with devise, omniauth and cancan. It all worked perfectly until I started to implement authorisation with cancan. It is even more interesting that cancan itself works like charm but generates an error in editing the user profile provided by devise. If cancan does that at all, I'm really not sure.
The error message is:
No route matches {:controller=>"devise/posts"}
I have a posts controller, but that's not linked to devise by any means. This is the strangest part in the story.
I successfully localised the spot that generates it but I can't figure out what the cause of the problem is and how to fix it. So I have a menu shown only to admins in my application.html.erb , this is the source:
<% if (user_signed_in? && (current_user.role?("sysadmin") || current_user.role?("postadmin") || current_user.role?("testadmin"))) %>
<ul class="nav navbar-nav nav-pills">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" style="color: crimson;">
<span class="glyphicon glyphicon-cog"></span> Administration <b class="caret"></b></a>
<ul class="dropdown-menu">
<% if (current_user.role?("sysadmin") || current_user.role?("postadmin")) then %>
<li><%= link_to 'Posts', :controller => :posts, :action => :index %></li>
<% end %>
<% if (current_user.role?("sysadmin") || current_user.role?("testadmin")) then %>
<li><%= link_to 'Itests', :controller => :itests, :action => :index %></li>
<% end %>
</ul>
</li>
</ul>
<% end %>
What's really interesting is that if I delete the <ul>...</ul> block so to leave nothing but a naked if ... end block, it works. Also, it works for users not having any of the three admin roles.
But in the <ul>...</ul> block there's nothing else but HTML, Bootstrap styling and some inline ruby links to some other controllers.
How does this breaks the "edit profile" feature of devise?
Check out this question: Rails No route matches {:controller=>"devise/products"}
Basically you're in device namespace and you have to use path helpers:
<%= link_to 'Posts', posts_path %>
or:
<%= link_to 'Posts', :controller => '/posts', :action => :index %>
I feel like I'm missing something really simple and I keep spinning my wheels on this problem.
I currently have internationalization working throughout my app. The translations work and the routes work perfectly. At least, most of the site works with the exception of the routes to my two static pages, my "About" and "FAQ" pages.
Every other link throughout the app points to the proper localized route. For example if I select "french" as my language, links point to the appropriate "(/:locale)/controller(.:format)." However, despite the changes I make throughout the app my links for the "About" and "FAQ" refuse to point to "../fr/static/about" and always point to "/static/about."
To make matters stranger, when I run rake routes I see:
"GET (/:locale)/static/:permalink(.:format) pages#show {:locale=>/en|fr/}"
and when I manually type in "../fr/static/about" the page translates perfectly.
My Routes file:
devise_for :users
scope "(:locale)", :locale => /en|fr/ do
get 'static/:permalink', :controller => 'pages', :action => 'show'
resources :places, only: [:index, :show, :destroy]
resources :homes, only: [:index, :show]
match '/:locale' => 'places#index'
get '/'=>'places#index',:as=>"root"
end
My ApplicationController:
before_filter :set_locale
def set_locale
I18n.locale=params[:locale]||I18n.default_locale
end
def default_url_options(options={})
logger.debug "default_url_options is passed options: #{options.inspect}\n"
{ :locale => I18n.locale }
end
and My Pages Controller:
class PagesController < ApplicationController
before_filter :validate_page
PAGES = ['about_us', 'faq']
def show
render params[:permalink]
end
def validate_page
redirect_to :status => 404 unless PAGES.include?(params[:permalink])
end
end
I'd be very grateful for any help ... it's just been one of those days.
Edit: Thanks to Terry for jogging me to include views.
<div class="container-fluid nav-collapse">
<ul class="nav">
<li class="dropdown">
<%= t(:'navbar.about') %><b class="caret"></b>
<ul class="dropdown-menu">
<li><%=link_to t(:'navbar.about_us'), "/static/about_us"%></li>
<li><%=link_to t(:'navbar.faq'), "/static/faq"%></li>
<li><%=link_to t(:'navbar.blog'), '#' %></li>
</ul>
</li>
You should give a name to your route by "as":
scope "(:locale)", :locale => /en|fr/ do
get 'static/:permalink', to: 'pages#show', as: :static
And then in view build link with routing helpers (route_name_path):
<li><%=link_to t('navbar.about_us'), static_path(permalink: "about_us") %></li>
This helper automatically add current locale to path.
To get list of all routes with names use rake routes console command.
Good luck!
Interesting. Ended up solving this problem by using url_for in the view:
<div class="container-fluid nav-collapse">
<ul class="nav">
<li class="dropdown">
<%= t(:'navbar.about') %><b class="caret"></b>
<ul class="dropdown-menu">
<li><%=link_to t(:'navbar.about_us'), url_for('static/about_us')%></li>
<li><%=link_to t(:'navbar.faq'), url_for('static/faq')%></li>
<li><%=link_to t(:'navbar.blog'), '#' %></li>
</ul>
</li>
I've personally never used url_for, so I'm not sure if this is the most graceful solution, however I'm happy that it works!
Edit:
Actually going back to code, this produced a really bad result. It worked from root_url and most other paths, however if the current path was /fr/static/about_us or /fr/static/faq the above lines actually called "/fr/static/static/about_us" or "/fr/static/static/faq" - rectified with:
<ul class="dropdown-menu">
<% if request.fullpath == '/fr/static/about_us' or request.fullpath == '/fr/static/faq' %>
<li><%=link_to t(:'navbar.about_us'), url_for('/fr/static/about_us')%></li>
<li><%=link_to t(:'navbar.faq'), url_for('/fr/static/faq')%></li>
<li><%=link_to t(:'navbar.blog'), '#' %></li>
<% elsif request.fullpath == '/en/static/about_us' or request.fullpath == '/en/static/faq' %>
<li><%=link_to t(:'navbar.about_us'), url_for('/en/static/about_us')%></li>
<li><%=link_to t(:'navbar.faq'), url_for('/en/static/faq')%></li>
<li><%=link_to t(:'navbar.blog'), '#' %></li>
<% elsif request.fullpath == '/static/about_us' or request.fullpath == '/static/faq' %>
<li><%=link_to t(:'navbar.about_us'), url_for('/en/static/about_us')%></li>
<li><%=link_to t(:'navbar.faq'), url_for('/en/static/faq')%></li>
<li><%=link_to t(:'navbar.blog'), '#' %></li>
<% else %>
<li><%=link_to t(:'navbar.about_us'), url_for('static/about_us')%></li>
<li><%=link_to t(:'navbar.faq'), url_for('static/faq')%></li>
<li><%=link_to t(:'navbar.blog'), '#' %></li>
<%end%>
</ul>
Moving on to another problem now, but if anyone has a more graceful way of doing this feel free to contribute. Will probably re-examine this problem early next week.
I saw a few postings related to this topic, but the given solutions did not really clarify things for me ...
So, I am working on a rails (version 3.2.2) application that followed the setup from Michael Hartl's Ruby on Rails tutorial. The application has a signout link, which worked well until recently, when it started giving me the error 'No route matches [GET] "/signout"'.
These are the relevant pieces:
routes.rb
match '/signout' => 'sessions#destroy', :via => :delete
sessions_controller.rb
def destroy
sign_out
redirect_to root_path
end
sessions_helper.rb
def sign_out
current_user = nil
cookies.delete(:remember_token)
end
_header.html.erb
<li>
<%= link_to "Sign out", signout_path, :method => :delete %>
</li>
All it takes for the signout to start working again is the removal of ":via => :delete" from the routes file. Is this the right approach or is there a better one? Also, why did the link stop working without any rails update?
Thank you,
Alexandra
On request, I added the full code for the _header.html.erb:
full _header.html.erb
<!-- ***** Initialized: Listing 5.24 ***** -->
<!-- ***** Updated: Listing 8.24 ***** -->
<!-- ***** Updated: Listing 9.7 ***** -->
<!-- ***** Begin: Listing 9.28 ***** -->
<header>
<header class="navbar navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<% if signed_in? %>
<%= link_to "project manager", about_path, id: "logo" %>
<% else %>
<%= link_to "project manager", root_path, id: "logo" %>
<% end %>
<nav>
<ul class="nav pull-right">
<!--li><%= link_to "Home", root_path %></li-->
<% if signed_in? %>
<% if Rails.env.development? %>
<li><%= link_to "Overview", overview_path %></li>
<% end %>
<% if Rails.env.development? %>
<li id="fat-menu" class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown"> Projects <b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li><%= link_to "Status", projects_path %></li>
<li><%= link_to "Dev View", dev_projects_path %></li>
</ul>
</li>
<% else %>
<li><%= link_to "Projects", projects_path %></li>
<% end %>
<% if Rails.env.development? %>
<li><%= link_to "Teams", teams_path %></li>
<% end %>
<% if Rails.env.development? %>
<li id="fat-menu" class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown"> Tasks <b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li><%= link_to "Status", tasks_status_path %></li>
<li><%= link_to "Tree", tasks_tree_path %></li>
<li><%= link_to "Dev View", dev_tasks_path %></li>
</ul>
</li>
<% else %>
<li id="fat-menu" class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown"> Tasks <b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li><%= link_to "Status View", tasks_status_path %></li>
<li><%= link_to "Tree View", tasks_tree_path %></li>
</ul>
</li>
<% end %>
<% if Rails.env.development? %>
<li id="fat-menu" class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown"> Reports <b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li><%= link_to "Project Progress", analysis_path %></li>
<li><%= link_to "Revision History", history_path %></li>
</ul>
</li>
<% else %>
<li id="fat-menu" class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown"> Reports <b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li><%= link_to "Revision History", history_path %></li>
</ul>
</li>
<% end %>
<% if Rails.env.development? %>
<li><%= link_to "Help", help_path %></li>
<% end %>
<li id="fat-menu" class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown"> Account <b class="caret"></b>
</a>
<ul class="dropdown-menu">
<% if current_user.admin? %>
<li><%= link_to "Admin", users_path %></li>
<% end %>
<% if Rails.env.development? %>
<li><%= link_to "Profile", current_user %></li>
<% end %>
<li><%= link_to "Settings", edit_user_path(current_user) %></li>
<li class="divider"></li>
<li>
<%= link_to "Sign out", signout_path, :method => :delete %>
</li>
</ul>
</li>
<% else %>
<li><%= link_to "Sign in", signin_path %></li>
<% end %>
</ul>
</nav>
</div>
</div>
</header>
<!-- ***** End: Listing 9.28 ***** -->
This thread is a bit old, but I thought I'd share a solution anyway as more people might be having the same problem.
Here is some background information on how this works before we get into the actual troubleshooting:
Notice that the Sign Out link looks as follows:
<%= link_to "Sign out", signout_path, :method "delete" %>
If you look at the source code generated by this tag, you will see this:
Sign out
Notice the part that says data-method="delete". With straight HTML, this won't work. If you click the link, your browser will simply ignore the DELETE instruction and instead submit a GET request to your server (this is what you are currently seeing in your log). To get your browser to submit a DELETE request, you will need to use some JavaScript magic. This is where the jquery_ujs.js file comes in (you will most likely be able to see a link to this file by Viewing Source in your browser; it should be in the header, close to, or included within the application.js file). If you look inside the jquery_ujs.js file, towards the middle of the file, you will see the following code:
// Handles "data-method" on links such as:
// Delete
In other words, the code above makes sure that your browser actually does submit a DELETE request (we don't have to get into the details of the actual code here).
Given this background information, there are two possible reasons why you are getting your error.
You are simply missing the jquery_ujs.js file
Other JavaScript code you have written or included is interfering with the desired
behavior of the jquery_ujs.js file
To troubleshoot, do as follows:
For 1) Load the page that contains your Sign Out link and select View Source from your browser. Make sure that the file jquery_ujs.js is in the header (or concatenated with the rest of your JS files into the application.js file, depending on your application settings)
For 2) In application.js, remove the //=require_tree . directive. Reload your page, and click the Sign Out link. If the Sign Out link is hidden under a menu that only works with your JavaScript installed, then just put a duplicate of the Sign Out link somewhere else on your page where it is accessible without JavaScript. Now try clicking on the link - it should hopefully work. If you are no longer getting the routing error, you know that this was the cause for your problem. The easiest way to troubleshoot this is to add back the //=require_tree . directive, but then to remove all your JavaScript files except the application.js file from the folder where they reside, and then to add back each file one by one, while you try the Sign Out link, until it no longer works. This will allow you to identify the troublemaker JavaScript file. Once you have identified this file, try removing all code (upon which the link should work again) and then adding back pieces of the code until it no longer works - voila, you have now identified the root of the problem! Please feel free to report back what it was. My guess is that it could be either a straight up error, a return false; statement, or a stopPropagation(); statement.
Hopefully this will work! Good luck.
Since the answers that I received in September 2012 did not solve my problem, I just ended up removing ":via => :delete" from the routes file, which made the signout link work again.
After reading eriklinde's answer, I went back to my code to see if his answer would help. The jquery_ujs.js file was not missing. So, I started looking into the second possible reason that was suggested. Nevertheless, when I went to the routes.rb file and added "via: :delete" to have a line reading "match '/signout', :to => 'sessions#destroy', via: :delete", the signout functionality continued working without a problem. Since "via: :delete" is different than ":via => :delete", which I previously removed, maybe this was causing the problem?
I think the solution is here:
Rails 3 link_to (:method => :delete) not working
Are you missing <%= javascript_include_tag :all %> in your page? It should go in your layout file.
I had this same problem and fixed it by rearranging the order of the requirements in the application.js file. Mine were ordered as such:
//= require jquery_ujs
//= require jquery
//= require bootstrap
//= require_tree .
and are now ordered like this
//= require jquery
//= require jquery_ujs
//= require bootstrap
//= require_tree .
I literally did nothing else.
try changing the _header.html.erb partial to
<li>
<%= link_to "Sign out", signout_path, :method "delete" %>
</li>
Actually you are probably missing the cross site forgery protection tags. Which would explain the inability to delete via the delete method. Not sure why it was working before.
Add this to your layout file in the head section
for haml
= csrf_meta_tags
for erb
<%= csrf_meta_tags %>
My guess would be that somehow you don't have jQuery UJS installed / active.
One of the key features listed here is "make non-GET requests from hyperlinks." Try adding gem 'jquery-rails' to your gemfile, run bundle install from the command line, restart your server, and see if it works!
This should be in your application.js file (with no lines above it that don't start with //!)
//= require jquery
//= require jquery_ujs
try this :
just add into you application.js
//= require jquery_ujs