`Couldn't find User without an ID` with Friendly_ID gem - ruby-on-rails

I am creating User Profiles with vanity URLs that use the username. The actual profile page works well, however I have my root page as the profile page if the user is signed in. If they are redirected to root then they get the error Couldn't find User without an ID and shows this code as the error pointing to the #user line...
class ProfilesController < ApplicationController
def show
#current_user = current_user
#user = User.friendly.find(params[:id])
#username = "#" + #user.username
#posting = Posting.new
end
end
Here is my routes file as well...
devise_for :users
# The priority is based upon order of creation: first created -> highest priority.
# See how all your routes lay out with "rake routes".
get "profiles/show"
devise_scope :user do
get '/register', to: 'devise/registrations#new', as: :register
get '/login', to: 'devise/sessions#new', as: :login
get '/logout', to: 'devise/sessions#destroy', as: :logout
get '/edit', to: 'devise/registrations#edit', as: :edit
end
authenticated :user do
devise_scope :user do
root to: "profiles#show", :as => "authenticated"
end
end
unauthenticated do
devise_scope :user do
root to: "devise/sessions#new", :as => "unauthenticated"
end
end
get '/:id' => 'profiles#show', as: :profile

This is not the problem with friendly id gem. The problem is that you are redirecting to a show method without supplying id, hence params[:id] is nil.
You can go around this by changing your show method:
def show
#current_user = current_user # why do you need this?
#user = params[:id] ? User.friendly.find(params[:id]) : current_user
#username = "#" + #user.username
#posting = Posting.new
end

Related

You are being redirected. Rails 5 + Devise

My rails application successfully logs out a user and redirects to the about page when in development mode. But the moment i deploy it to production it returns a 302 status and a page that shows "you are being redirected". Am using devise for authentication below is what my code actually looks like.
The routes
Rails.application.routes.draw do
devise_for :users, controllers: { registrations: "users/registrations", confirmations: "users/confirmations", sessions: "devise/sessions" }, skip: [:sessions]
devise_scope :user do
get "login" => "devise/sessions#new", as: :new_user_session
post "login" => "devise/sessions#create", as: :user_session
get "/join" => "users/registrations#new", as: :join
get '/logout', to: "devise/sessions#destroy", as: :destroy_user_session
end
resources :companies
get "/about", to: "pages#about"
get "/faq", to: "pages#faq"
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
root 'pages#home'
end
My application_controller.rb
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
include SessionsHelper
protected
def after_sign_in_path_for(resource)
company_path(resource)
end
def after_sign_out_path_for(resource_or_scope)
"/about"
end
def store_location
session[:return_to] == request.full_path
end
def clear_stored_location
session[:return_to] = nil
end
def redirect_back_or_to(alternate)
redirect_to(session[:return_to] || alternate)
clear_stored_location
end
end
And finally my link to log out.
<%= link_to "Log out", destroy_user_session_path %>
Please note that i am using devise 4.2.0 and capistrano for deployment.
Regards
~
I had to override devise sessions#controller and changed my routes to:
delete 'logout', to: "users/sessions#destroy", as: :destroy_user_session
Then i added delete method to my link for logging out.

Rails: How to render different versions of a "show" view

I have a model "User". I defined it in my routes.rb with resources :users. I want to be able to render different versions of the same user. To see if it would work, here's what I tried in my routes.rb:
get "users/:id_alt", :to => "users#alt", :as => :user
and in my controller:
def show
#user = User.find(params[:id])
end
def alt
#user = User.find(params[:id])
end
But when I navigated to users/1, I got this error:
ActiveRecord::RecordNotFound in UsersController#alt
Couldn't find User without an ID
and the error pointed to this line under def alt:
#user = User.find(params[:id])
Anyone know how to remedy this error or accomplish this another way?
It is because you have set your route to use :id_alt
get "users/:id_alt", :to => "users#alt", :as => :user
So the controller is assuming the value in that location should have the name :id_alt not :id. You are not going to be able to have both routes set up this way, but you could do this:
get "users/alt/:id_alt", :to => "users#alt", :as => :alt_user
get "users/:id", :to => "users#show", :as => :user
You will be able to use these path methods: alt_user_path and user_path
And your controller should look like this:
def show
#user = User.find(params[:id])
end
def alt
#user = User.find(params[:id_alt])
render :show
end
Running rake routes will result in this:
alt_user GET /users/alt/:id_alt(.:format) users#alt
user GET /users/:id(.:format) users#show

Acts as follower Set Up

I'm trying to get acts_as_follower working but i'm missing something. A user should be able to Follow another User.
I added the Gem :
gem "acts_as_follower", '~> 0.2.0' #0.2.0 for Rails 4
In my User model i added :
acts_as_follower
acts_as_followable
The User Controller i created looks like this :
class UsersController < ApplicationController
def show
#user = User.find(params[:id])
end
def follow
#user = User.find(params[:id])
current_user.follow(#user)
redirect_to :back
end
end
My routes :
App::Application.routes.draw do
root 'screens#index'
devise_for :users
get 'u/:id' => 'users#show', as: :user
resources :screens, :path => 's' do
member do
get :like
get :unlike
end
end
get "pages/home"
get "about" => "pages#about"
get "users/show"
end
now in the routes i have to add the member :follow =>
member do
get :follow
end
But i'm stuck at this point. I tried a few variations and my link to follow a User is :
<%= link_to "Follow", follow_user_path(#user)%>
and this is giving me the error ->
undefined method `follow_users_path' for #<#<Class:0x007fb4da78e920>:0x007fb4db3facb8>
The Solution was to create a user resource, it works perfectly now =>
resources :users do
member do
get :follow
get :unfollow
end
end

Rake routes 'match' mapping to the wrong action

My question has to do with mapping to controllers/actions using named routes. I am trying to map '/profile' to 'customers#show'. My routes file looks like this:
root :to => 'pages#home'
## named routes
match "profile" => "customers#show", :as => 'profile'
match 'signin' => 'sessions#new', :as => 'signin'
match 'signout' => 'sessions#destroy', :as => 'signout'
resources :customers do
member do
get 'add_card'
post 'submit_card'
end
end
resources :payments, :only => [:show, :new]
delete 'payments/delete_recurring_payment'
post 'payments/submit_non_recurring'
post 'payments/submit_recurring'
resources :sessions, :only => [:create, :destroy, :new]
Running 'rake routes' gives me this:
root / pages#home
profile /profile(.:format) customers#show
signin /signin(.:format) sessions#new
signout /signout(.:format) sessions#destroy
add_card_customer GET /customers/:id/add_card(.:format) customers#add_card
submit_card_customer POST /customers/:id/submit_card(.:format) customers#submit_card
customers GET /customers(.:format) customers#index
POST /customers(.:format) customers#create
new_customer GET /customers/new(.:format) customers#new
edit_customer GET /customers/:id/edit(.:format) customers#edit
customer GET /customers/:id(.:format) customers#show
PUT /customers/:id(.:format) customers#update
DELETE /customers/:id(.:format) customers#destroy
new_payment GET /payments/new(.:format) payments#new
payment GET /payments/:id(.:format) payments#show
Here is where I'm stumped. When I go to localhost:3000/profile I get a routing error saying this:
No route matches {:action=>"edit", :controller=>"customers"}
This seems odd because there is indeed a route to 'customers#edit' due to my declaring customers as a resource.
However, when I go to 'localhost:3000/signin' I get routed to 'customers#show' which is where I want '/profile' to route to.
It seems like my routes are 'one off' in my routes file but I have no idea why. Any help would be much appreciated.
Thanks
UPDATE 1: Adding my Customers Controller
class CustomersController < ApplicationController
layout "payments_layout"
def show
#customer = current_user
get_account_info(#customer)
get_payment_history(#customer, 10)
end
def new
#title = 'Create an account'
#customer = Customer.new
end
def edit
#customer = current_user
get_account_info(#customer)
end
def update
#customer = current_user
if #customer.update(params[:customer])
redirect_to #customer
else
#card_message = "Use this form to add a credit card to your account. You must have a credit card associated with your account in
in order to make payments on our system."
get_account_info(#customer)
render 'edit'
end
end
def create
#customer = Customer.new(params[:customer])
if #customer.save_and_get_stripe_id
sign_in(#customer)
redirect_to #customer
else
#title = 'Create an account'
render 'new'
end
end
def add_card
#customer = current_user
get_account_info(#customer)
#card_message = "Use this form to add a credit card to your account. You must have a credit card associated with your account in
in order to make payments on our system."
end
def submit_card
#customer = current_user
res = #customer.add_or_update_card(params)
if res
redirect_to #customer
else
#error = res
customer.get_account_info(#customer)
render 'add_card'
end
end
end
Check your views.
Do you have a link to edit your user profile?
It seems like you actually route to the right controller and action but have some links that rake can't route, e.g. you don't pass the ID to your edit_customer_path link.

Setting Devise Login to be root page

I am using the following code for my routes:
devise_for :user,
:as => '',
:path_names => {
:sign_in => "",
:sign_out => "logout",
:sign_up => "register"
}
But when I'm logged out and I goto /logout I get the following error:
No route matches {:action=>"new",
:controller=>"devise/sessions"}
How do I setup the root path to be to :sign_in action?
To follow on from the people who are asking about the error Could not find devise mapping for path "/" there is a workaround.
You'll find that there is a clue in your logs which will probably say:
[Devise] Could not find devise mapping for path "/".
This may happen for two reasons:
1) You forgot to wrap your route inside the scope block. For example:
devise_scope :user do
match "/some/route" => "some_devise_controller"
end
2) You are testing a Devise controller bypassing the router.
If so, you can explicitly tell Devise which mapping to use:
#request.env["devise.mapping"] = Devise.mappings[:user]
So I retried the approach but instead wrapping it (as #miccet suggets) inside a scope block:
devise_scope :user do
root to: "devise/sessions#new"
end
This worked fine for me
devise_for :users
devise_scope :user do
authenticated :user do
root 'home#index', as: :authenticated_root
end
unauthenticated do
root 'devise/sessions#new', as: :unauthenticated_root
end
end
Just like this, tested on Rails Rails 4.1.0.rc1.
root :to => "devise/sessions#new"
I needed to set the default home root. I felt like I had tried this all night last night (prior to posting the question), but it's working now. If you're logged out, Devise attempts to redirect you to the root path which I had undefined.
(This was posted as a suggested edit, but should have been an answer of its own. I don't know if it makes sense or not. Dear anonymous editor: feel free to repost this answer as your own, and leave me a comment so I'll delete this copy.)
root :to => redirect("/users/login")
I got this to work with #VvDPzZ answer. But I had to modify it slightly
devise_scope :business_owner do
authenticated do
root to: 'pages#dashboard'
end
unauthenticated do
root to: 'devise/sessions#new', as: 'unauthenticated_root'
end
end
I had to ad to: in the root path declaration. I also removed the as: :authenticated_root because I already had some places in my application referencing root_path in links. By leaving out the as: :authenticated_root part I didn't have to change any of my existing links.
I guess you have different user roles. If you do you have to add a scope like this to the users resource:
devise_scope :user do
get "/logout" => "devise/sessions#destroy"
end
You can read more about overriding devise routes here:
https://github.com/plataformatec/devise/wiki/How-To:-Change-the-default-sign_in-and-sign_out-routes
Some of these solutions are way too complex. Just use Rails:
Add 'get' 'users/root', to: 'users#root' to config/routes.rb.
In UsersController do something like:
def root
if user_signed_in?
redirect_to root_for_signed_in_user_path (or whatever)
else
redirect_to new_user_session_path
end
end
Using rails 3.2 and devise 3.2.3 I manage to setup my home page "home#index" (controller#action) as the login page making the following changes.
#1 Added the login form to the home page:
<%= simple_form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %>
<%= f.input :email %>
<%= f.input :password %>
<%= f.button :submit %>
<% end %>
#2 Added methods resource_name, resource and devise_mapping to app/heldpers/application_helper.rb:
def resource_name
:user
end
def resource
#resource ||= User.new
end
def devise_mapping
#devise_mapping ||= Devise.mappings[:user]
end
#3 Created a custom sessions controller app/controllers/users/sessions_controller.rb:
class Users::SessionsController < Devise::SessionsController
protected
# This method tell sessions#create method to redirect to home#index when login fails.
def auth_options
{ scope: resource_name, recall: 'home#index' }
end
end
#4 Skip the session routes and setup the custom sessions controller in config/routes.rb:
devise_for :users, path: 'auth', skip: [:sessions],
controllers: {
sessions: 'users/sessions'
}
as :user do
get 'auth/sign_in' => 'home#index', as: :new_user_session
post 'auth/sign_in' => 'users/sessions#create', as: :user_session
delete 'auth/sign_out' => 'users/sessions#destroy', as: :destroy_user_session
end
I'm new on rails and I didn't know your 'device_scope' name have to be different to your 'device_for' name. Notice my example.
I tried this a hundred times a this is why it didn't work jajaja
devise_for :user_devises, path: 'user_devises'
devise_scope :user_devise do
authenticated :user_devise do
root 'home#index', as: :authenticated_root
end
unauthenticated do
root 'devise/sessions#new', as: :unauthenticated_root
end
end

Resources