I have a very basic sign up and log in setup running and all I want to know if how to add a link at the very top of my root page that displays 'Log in' or 'Sign out' depending on whether the user is logged in or not.
I have tried various methods I have found on here but can't seem to get them to work as they often create undefined method errors.
What is the simplest way to create this?
Many thanks in advance for your help.
Tom
if you have a session variable where you save the id of the current user (i call it user_id) you could do it like this:
<% if session[:user_id] %>
<!-- user is logged in -->
<%= link_to logout_path %>
<% else %>
<!-- user is not logged in -->
<%= link_to login_path %>
<% end %>
that is what you have to change:
config/routes.rb:
resources :users
# login stuff
controller :sessions do
get "login" => "sessions#new"
post "login" => "sessions#create"
delete "logout" => "sessions#destroy"
end
app/views/sessions/new.html.erb:
# replace this line
<%= form_tag new_session_path do %>
# with
<%= form_tag login_path do %>
the login link is now:
<%= link_to "Login", login_path %>
the logout link:
<%= link_to "Logout", logout_path, :method => :delete %>
Not much of an answer but this Railscast was very helpful to me in learning about how authentication works in rails. The Railscast is Twitter login specific using OmniAuth but the process is much the same. He includes the dynamic links you asked about in his code.
http://railscasts.com/episodes/241-simple-omniauth
Related
I'm following the Rails Tutorial by Michael Hartl to build a tiny demo app. I'm stuck at the logout. This is my routes.rb:
Rails.application.routes.draw do
resources :users
get "/login", to: "sessions#new"
post "/login", to: "sessions#create"
delete "/logout", to: "sessions#destroy"
# Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html
# Defines the root path route ("/")
root 'users#index'
end
This is the relevant controller action:
def destroy
log_out
redirect_to root_url, status: :see_other
end
This is the session helper defining log_out:
def log_out
reset_session
#current_user = nil
end
and this is the link tag in the view:
<%= link_to "Log out", logout_path, data: { 'turbo-method': :delete } %></span>
Screenshot of error
When I click on the logout link, I get this error. Expected behaviour: Log user out, redirect to login screen.
What am I doing wrong?
I don't know whether it's because of Turbo, or whether Turbo is even correctly installed. I've added gem 'turbo-rails' to the Gemfile and ran bundle afterwards without any effect.
For me, adding the method: :delete worked along with data-turbo.
<span>
<%= link_to "Log out", destroy_user_session_path,method: :delete, data: { 'turbo-method': :delete } %></span>
You were accessing the DELETE method route via GET. Have you run
rails turbo:install
You may want to change the sign out via GET instead of Delete in config/devise.rb
# The default HTTP method used to sign out a resource. Default is :delete.
config.sign_out_via = :get # <= change this from :delete to :get and remove the `method:` in your `link_to` helper
Here's the references:
https://github.com/hotwired/turbo-rails
https://github.com/heartcombo/devise/issues/5439
Check with passing method
<%= link_to "Log out", logout_path, method: :delete, data: { 'turbo-method': :delete } %>
or
<%= link_to "Log out", logout_path, method: :delete %>
You can change link_to to button_to
<%= button_to "Log out", logout_path, method: :delete %>
It will be less magic but more reliable because not a link but form is used (in normal life, clicking on link is a GET request)
Working on versions:
Ruby: 3.0.2
Rails 6.1.4
I'm trying to put a button in my View template for "Users" that will set the :mod attribute to false, with the button just being "Demote User".
I had it working SOMEHOW using a helper method, demote_user, and some variation of
<% if logged_in? && current_user.admin? %>
<%= link_to "Demote User", user_path(#user), onclick: demote_user(#user), class: "btn btn-info" %>
<% end %>
I messed up however it was working when trying to move this method into a controller for best practice. I'm not sure what format worked out, but I've tried many such as
:onclick => demote_user(#user)
onclick: 'demote_user(#user)'
onclick=demote_user(#user)
onclick='demote_user(#user)
and etc. Somehow, it did eventually work but I busted it. Now, every time I load the User's page, it's just executing demote_user(#user) without even needing to click the button, so refreshing a User's page is demoting them.
I am now trying to do this properly by creating a demote method in the UserController, but I have NO IDEA how to make the route, or make it work properly. Up until now, all my routes have been working using resources, and the basic new, create, destroy, etc.
I've been trying many different routes, and view formatting, with no luck and usually ending up with just: Routing Error
No route matches [GET] "/demote.3"
I'd like to be able to avoid using the Javascript onClick functionality and do it properly with the controller even if I could remember how to make it work, but I think my route, or view page, or controller is incorrect. Here are the contents of each file:
Controller
def demote
byebug
#user = User.find(params[:id])
#user.mod = false
redirect_to user_path(#user)
end
View
div class="container text-center mt-4">
<% if logged_in? && current_user.admin? %>
<%= link_to "Demote User", demote_path(#user), class: "btn btn-info" %>
<% end %>
</div>
Routes
Rails.application.routes.draw do
root 'pages#home'
get 'about', to: 'pages#about'
resources :articles
get 'signup', to: 'users#new'
resources :users, except: [:new]
get 'login', to: 'sessions#new'
post 'login', to: 'sessions#create'
delete 'logout', to: 'sessions#destroy'
resources :categories
post 'demote', to: 'users#demote'
end
Up until now, I've been following a course, and I've nailed everything in it and have added some of my own functionality, but I'm still not quite sure how to make sense of routes, or what paths it creates.
I'd like to make other similar custom controller functions beyond show, index, create, delete, update which are all I really understand how to build. I'm not even sure if POST is the correct call in the route.
I would just setup an additional RESTful action for the resource:
resources :users do
patch :demote
end
<% if logged_in? && current_user.admin? %>
<%= button_to "Demote User", demote_user_path(#user), method: :patch %>
<% end %>
You can use link_to instead of button_to but you need to use the correct method: :patch or data: { turbo_method: :patch } option depending on your version of Rails to get the javascript driver to do its trickery.
I am using the Gem 'Devise' in order to set users and admins for my page. I have created a log in page which requires the user to first sign in and then after the succesful log in I want to redirect the user to the home page of the Model Category, which is gonna be displaying just a list of categories of products. Yet, I have not found the proper way to do it. This is my routes file:
Rails.application.routes.draw do
resources :categories
root to: 'pages#home'
devise_for :users
end
And this is my home.html.erb file inside the view pages :
<h1>Login page</h1>
<% if current_user %>
<%= link_to 'Categories', category_path(#category) %>
<%= link_to 'Sign Out', destroy_user_session_path, method:
:delete %>
<% else %>
<%= link_to 'Sign Up', new_user_registration_path %>
<%= link_to 'Sign In', new_user_session_path %>
<% end %>
I get an error saying:
ActionView::Template::Error
(No route matches {:action=>"show",:controller=>"categories", :id=>nil},
missing required keys: [:id]):
How can I connect the home.html.erb file of the view Page with the index.html.erb of the Category view? Thanks in advance for any help provided
How can I connect the home.html.erb file of the view Page with the index.html.erb of the Category view?
If what you want is a link to view all categories, then why are you using a helper to view one singular category, category_path(#category) (and passing a non-existing #category too)? Instead, use this:
<%= link_to 'Categories', categories_path %>
In my small rails app I have a controller called say and two pages hello and goodbye in it. I installed devise in the app. Initially i was able to access the sing_in page as /users/sign_in and similarly for sign up. I was not able to sign out and due to not able to sign out i am not able to access sign up or sign in page again. Now I entered the following code int eh say/hello page
<h1>Say#hello</h1>
<% if user_signed_in? %>
Hey signed in as <%= current_user.email %>.Not you?
<%= link_to "Logout", destroy_user_session_path %>
<% else %>
Hey <%= link_to "Login", new_user_session_path %> or Hey <%= link_to "Logup", new_user_registration_path %>
<% end %>
</p>
This the routes page of the app.
Demo::Application.routes.draw do
devise_for :users
get "say/hello"
get "say/goodbye"
# The priority is based upon order of creation: first created -> highest priority.
# See how all your routes lay out with "rake routes".
# You can have the root of your site routed with "root"
root :to => "say#hello"
end
Whenever I access the say/hello page, this is the output i get
Links
Hey signed in as x#gmail.com.Not you? Logout
When I click logout. It says
No route matches [GET] "/users/sign_out"
When I directly access users/sign_in I get routed to the say/hello page.
What mistake am I doing? How should I sign_out?
I have also tried
destroy_user_session_path, :method => :delete
Hope this could help
Try this in your routes.rb
devise_for :users do get '/users/sign_out' => 'devise/sessions#destroy' end
I have a rails 3 app, and when I click the link to my terms page, it routes to a completely different controller, than what the routes should use. Stranger still, the route works when I'm not logged in, and I'm using devise.
I get this error when clicking the link when I'm logged in.
No route matches {:action=>"edit", :controller=>"users", :id=>nil}
<%= link_to "Terms", terms_path %>
Routes (in the order they appear in routes.rb):
devise_for :users, :controllers => {:registrations => "registrations"}
resources :users do
member do
get :following, :followers
post :accept
end
end
match '/terms', to: 'static_pages#user_agreement'
Static Pages Controller
def user_agreement
end
Rake Routes
terms /terms(.:format) static_pages#user_agreement
This also happens for every other action that I've routed this way to the staticpages controller, but not for any other actions that route to different controller.
Update: Terms Page
Header:
<%= link_to "Follow", users_path %>
<%= link_to current_user.name, current_user %>
<%= link_to "Sign out", destroy_user_session_path, :method => :delete %>
Footer:
<%= link_to "Welcome", welcome_path %>
<%= link_to "Settings", edit_user_path(#user) %>
<%= link_to "Terms", terms_path %>
All the content is pure html.
Thanks in advance
You have a link to edit_user_path with no #user as hinted in the comments.
You should almost certainly be using current_user anyway.