I am trying to de-active user from my rails application. However, this is not working at the moment.
My routes file -
# Root is the unauthenticated path
root 'sessions#unauth'
# Sessions URL
get 'sessions/unauth', to: 'sessions#unauth', as: :login
post 'sessions/login', as: :signin
delete 'sessions/logout', as: :logout
# Resourceful routes for articles
resources :articles
get '/interests', to: 'articles#my_interests', as: 'interests'
get '/destroy', to: 'users#destroy', as: 'destroy_user'
resources :users, only: [:create,:new,:update,:destroy,:edit]
Then I have a html file inside layout folder.
<li><%= link_to "De-activate User", destroy_user_path(current_user)%></li>
User will be clicking De-active User button, and I am expecting action to go into my Users Controller. Below is my UsersController.rb.
class UsersController < ApplicationController
before_action :set_user, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user, only: [:edit, :destroy, :update]
before_action :check_valid, only: [:edit, :destroy, :update]
# DELETE /users/1
# DELETE /users/1.json
def destroy
log_out #user
#user.destroy
respond_to do |format|
format.html { redirect_to login_path, notice: 'user was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_user
#user = User.find(params[:id])
end
def check_valid
unless #user==current_user
redirect_to articles_path
end
end
# Never trust parameters from the scary internet, only allow the white list through.
def user_params
params.require(:user).permit(:first_name, :last_name, :email, :bio, :username, :password, :interest_list, :password_confirmation)
end
end
Rails give me error in the set_user method.
Error - Couldn't find User with 'id'= at #user = User.find(params[:id])
I am not able to understand what is the issue over here?
My log_out method -
def log_out
session[:user_id] = nil
end
Try this
<li><%= link_to "De-activate User", destroy_user_path(current_user), method: :delete%></li>
Thanks
You have override your default path that generated by resources :users with:
get '/destroy', to: 'users#destroy', as: 'destroy_user'
If you properly see your built route you can not find params[:id]. With this route you can go to action but could not find params[:id] there.
You can change your route like this :
get '/destroy/:id', to: 'users#destroy', as: 'destroy_user'
So your cuurent code will work properly.
Please try this:
<%= link_to "De-activate User", current_user, method: :delete %>
OR
<%= link_to "De-activate User", user_path(current_user), method: :delete %>
Related
I am trying to write an update function, which allows to pick a user in a list of users and update that user to make it an admin. The important function in the controller should be def change_admin.
Thanks for your help!
I tried several options, but I run into that error:
Couldn't find User with 'id'=
My Controller:
class UsersController < ApplicationController
before_action :logged_in_user, only: [:index, :edit, :update, :destroy]
before_action :correct_user, only: [:edit, :update]
before_action :admin_user, only: :destroy
def new
#user = User.new
end
def index
#users = User.where(activated: true).paginate(page: params[:page])
end
def show
#user = User.find(params[:id])
redirect_to root_url and return unless #user.activated
end
def edit
end
def destroy
User.find(params[:id]).destroy
flash[:success] = "Der Nutzer wurde gelöscht"
redirect_to users_url
end
def update
#user = User.find(params[:id])
if #user.update_attributes(user_params)
redirect_to root_path
else
render 'edit'
end
end
def create
#user = User.new(user_params)
if #user.save
#user.send_activation_email
flash[:info] = "Bitte öffnen Sie Ihr E-Mail Postfach, um den Account zu aktivieren."
redirect_to root_url
else
render 'new'
end
end
def admin
#users = User.where(activated: true).paginate(page: params[:page])
end
def change_admin
#user = User.find(params[:id])
#user.update_attribute(:admin,true)
respond_to do |format|
format.html { redirect_to admin_path }
end
end
# Before filters
# Confirms the correct user.
def correct_user
#user = User.find(params[:id])
redirect_to(root_url) unless current_user?(#user)
end
private
def user_params
params.require(:user).permit(:name, :email, :password, :password_confirmation,
:mat_number, :ects, :grade_avg, :enrolled, :matched_institute)
end
def admin_user
redirect_to(root_url) unless current_user.admin?
end
end
I also tried to delete the user.find line, but that gives me another error:
undefined method `update_attribute' for nil:NilClass
My routes file:
Rails.application.routes.draw do
resources :preferences
resources :institutes
get 'password_resets/new'
get 'password_resets/edit'
get '/users_show', to: 'users#show'
get '/users/new'
root 'static_pages#home'
get '/home', to: 'static_pages#home'
get '/help', to: 'static_pages#help'
get '/about', to: 'static_pages#about'
get '/contact', to: 'static_pages#contact'
get '/matching', to: 'static_pages#matching'
get '/signup', to: 'users#new'
post '/signup', to: 'users#create'
get '/admin', to: 'users#admin'
post '/change_admin', :to => 'users#change_admin', as: 'change_admin'
get '/performance_show', to: 'users#performance_show'
get '/performance_update', to: 'users#performance_update'
post 'preferences/create_all', :to => 'preferences#create_all'
get '/login', to: 'sessions#new'
post '/login', to: 'sessions#create'
delete '/logout', to: 'sessions#destroy'
resources :users
resources :account_activations, only: [:edit]
resources :password_resets, only: [:new, :create, :edit, :update]
post 'preferences/delete_matching', :to => 'preferences#delete_matching'
post 'preferences/read_and_show_ofv', :to => 'preferences#read_and_show_ofv'
post 'preferences/read_matching', :to => 'preferences#read_matching'
post 'preferences/optimize_matching', :to => 'preferences#optimize_matching'
post 'preferences/optimize', to: 'preferences#optimize'
end
Your routes are in pretty bad shape. You have tons of duplication as well as routes that are missing the :id segment to make them work:
get '/users_show', to: 'users#show'
get '/users/new'
post '/change_admin', :to => 'users#change_admin', as: 'change_admin'
resources :users already declares a proper show route as GET /users/:id and new as /users/new.
To add additional RESTful routes you should instead pass a block to resources:
resources :users do
# this should be PATCH not POST
patch :change_admin
end
This will create the proper route as /users/:id/change_admin.
You are also using the wrong HTTP verb in many places like for example get '/performance_update', to: 'users#performance_update'. Never use GET for actions that create or alter a resource as the call ends up in the browsers history and may be cached.
Adding update, change, create in the path of your route should be a big red flag that you´re doing it wrong.
I would recommend that you read the guides thoroughly before adding more cruft.
Ok... so now I'm at day 2 trying to figure out why on my development env, it works but when I deploy my app to production it doesn't work.
I'm simply trying to create a "like/upvote" button and count the "likes/upvotes" on every post, and then do the same for every comment in a post.
Since I'm using friendly_id to create a slug from the :title field, I'm getting this in my Heroku Logs:
ActionController::RoutingError (No route matches [GET] "/posts/test/upvote"):
I obviously get the "This page doesn't exist" error...
Here's the code:
routes.rb
resources :posts, only: [:create, :index, :show, :destroy, :edit, :update] do
resources :comments, only: [:show, :create, :destroy, :edit, :update] do
member do
put '/upvote' => 'comments#upvote'
end
end
member do
put '/upvote' => 'posts#upvote'
end
end
end
post_controller.rb
def upvote
#post = Post.friendly.find(params[:id])
#post.increment!(:upvotes)
redirect_to root_path
end
comments_controller.rb
def upvote
#post = Post.friendly.find(params[:post_id])
#comment = #post.comments.find(params[:id])
#comment.increment!(:upvotes)
redirect_to #post
end
post index.html.erb
<%= link_to "like", upvote_post_path(post), method: :put, style: "color: white;" %>
What's missing here that I'm not seeing?
I've done Michael Hartl Ruby on Rails 5 tutorial and am now trying to apply the code to my own app.
What I'm trying to do is:
Follow/Unfollow an event
Display total count of users following this event
Users can see all the events that they are following
The current error appears when I try to render the conferences that current user is following.
The error that I get is:
ActionController::UrlGenerationError in Users#show
No route matches {:action=>"followers", :controller=>"conferences", :id=>nil} missing required keys: [:id]
The line that causes the problem is:
<a href="<%= followers_conference_path(#conference) %>">
Now obviously their is something wrong in my routing and I assume the following problem states that conferences is missing a required id?
Does anyone know the solution to my problem? Which is getting allowing users to follow events and see what events they are following
USER CONTROLLER SHOW
def show
#user = User.find(params[:id])
#microposts = #user.microposts.paginate(page: params[:page])
#managments = #user.managments.paginate(page: params[:page])
#conference = Conference.find(params[:id])
end
ROUTES.RB
Rails.application.routes.draw do
root 'static_pages#home'
get '/help', to: 'static_pages#help'
get '/about', to: 'static_pages#about'
get '/contact', to: 'static_pages#contact'
get '/my_conference', to: 'my_conference#show'
get '/conferences', to: 'conferences#index'
get '/conferences_list', to: 'conferences#index_admin'
get '/my_employees', to: 'employees#index'
get '/signup', to: 'users#new'
get '/login', to: 'sessions#new'
post '/login', to: 'sessions#create'
delete '/logout', to: 'sessions#destroy'
get '/login', to: 'sessions#new'
put 'activate/:id(.:format)', :to => 'users#activate', :as => :activate_user
put 'deactivate/:id(.:format)', :to => 'users#deactivate', :as => :deactivate_user
put 'activate_employee/:id(.:format)', :to => 'employees#activate', :as => :activate_employee
put 'deactivate_employee/:id(.:format)', :to => 'employees#deactivate', :as => :deactivate_employee
resources :users do
member do
get :following
end
end
resources :conferences do
member do
get :followers
end
end
resources :articles
resources :users
resources :employees
resources :account_activations, only: [:edit]
resources :activations, only: [:edit]
resources :password_resets, only: [:new, :create, :edit, :update]
resources :microposts, only: [:create, :destroy]
resources :managments
resources :conferences
resources :relationships, only: [:create, :destroy]
end
CONFERENCES_CONTROLLER.RB
class ConferencesController < ApplicationController
before_action :logged_in_user, only: [:create, :destroy]
before_action :correct_user, only: :destroy
before_action :admin_user, only: :destroy
def index
#conferences = Conference.paginate(page: params[:page])
if params[:search]
#conferences = Conference.search(params[:search]).order("created_at DESC").paginate(page: params[:page])
else
#conferences = Conference.all.order('created_at DESC').paginate(page: params[:page])
end
end
def new
#user = User.new
#conference = Conference.new
end
def create
#conference = current_user.conferences.build(conference_params)
if #conference.save
flash[:success] = "conference created!"
redirect_to conferences_path
else
#feed_items = current_user.feed.paginate(page: params[:page])
render 'new'
end
end
def destroy
#conference.destroy
flash[:success] = "conference deleted"
redirect_to request.referrer || root_url
end
def following
#title = "Following"
#conference = Conference.find(params[:id])
#conferences = #conference.following.paginate(page: params[:page])
render 'show_follow'
end
def followers
#title = "Followers"
#user = User.find(params[:id])
#users = #user.followers.paginate(page: params[:page])
render 'show_follow'
end
private
def conference_params
params.require(:conference).permit(:conference,:country , :month, :presence, :audience, :cost ,:picture)
end
# Confirms an admin user.
def admin_user
redirect_to(root_url) unless current_user.admin?
end
def correct_user
#conference = current_user.conferences.find_by(id: params[:id])
redirect_to root_url if #conference.nil?
end
end
Ahh, i see the issue.
Check your UsersController#show to see if #conference is being set anywhere.
If not try: <a href="<%= followers_conference_path(current_user.id) %>">
You don't want to use the user id to get the #conference object, I'm sure. Instead, you are probably generating a list of conferences the user is following. In that case, you'd use something like this
<% #user.conferences.each do |conference| %>
<%= conference.name %>
<% end %>
And, in Rails, you would usually use the link_to helper, and maybe include a count to show how many followers the conference has.
<% #user.conferences.each do |conference| %>
<%= link_to conference.name, followers_conference_path(conference) %>
(<%= pluralize conference.users.count, 'follower' %>)
<% end %>
I am still very much new to rails, but cant seem to get a grasp on this route
show.html.erb
<%= link_to "up", vote_movie_review_path(#review, type: "up"), method: "post" %>
rake route
vote_movie_review POST /movies/:movie_id/reviews/:id/vote(.:format) reviews#vote
routes.rb
Rails.application.routes.draw do
devise_for :users
resources :movies do
resources :reviews do
member { post :vote }
end
end
reviews_controller.rb
class ReviewsController < ApplicationController
before_action :set_reviews, only: [:show, :edit, :update, :destroy]
before_action :set_movie
before_action :authenticate_user!
respond_to :html
def index
#reviews = Review.all
respond_with(#reviews)
end
def show
end
def vote
value - params[:type] == "up" ? 1 : -1
#review = Review.find(params[:id])
#review.add_evaluation(:votes, value, current_user)
redirect_to :back, notice: "thanks for the vote"
end
You are using nested routes, so you need to pass movie object also.use like this vote_movie_review_path(#movies, #review, type: "up").
Check your routes, it showing /movies/:movie_id/reviews/:id/vote while the way you are calling it will generate like /reviews/id with method post and for it you have not defined any routes.
I cannot figure out why I am getting this error. I know this question is very similar to this question, but I have all the jquery links correct as verified by the fact that I can delete users without a problem but not the microposts. When I try the example in the browser and click the delete link(http://localhost:3000/microposts/253) on a micropost, even though the item does get deleted the browser says:
Routing Error
No route matches [GET] "/microposts/253"
Try running rake routes for more information on available routes.
Test result:
Micropost pages micropost destruction as correct user should delete a micropost
Failure/Error: expect { click_link "delete" }.should change(Micropost, :count).by(-1)
ActionController::RoutingError:
No route matches [GET] "/microposts/1"
routes.rb
resources :users
resources :sessions, only: [:new, :create, :destroy]
resources :microposts, only: [:create, :destroy]
match '/signup', to: 'users#new'
match '/signin', to: 'sessions#new'
match '/signout', to: 'sessions#destroy', via: :delete
match '/help', to: 'static_pages#help'
match '/about', to: 'static_pages#about'
match '/contact', to: 'static_pages#contact'
root to: 'static_pages#home'...
Microposts delete link:
<%= link_to "delete", micropost, method: :delete,
confirm: "You sure?",
title: micropost.content %>
Microposts controller:
class MicropostsController < ApplicationController
before_filter :signed_in_user, only: [:create, :destroy]
before_filter :correct_user, only: :destroy
def create
#micropost = current_user.microposts.build(params[:micropost])
if #micropost.save
flash[:success] = "Micropost created!"
redirect_to root_path
else
#feed_items = []
render 'static_pages/home'
end
end
def destroy
#micropost.destroy
redirect_back_or root_path
end
private
def correct_user
#micropost = current_user.microposts.find_by_id(params[:id])
redirect_to root_path if #micropost.nil?
end
end
I am unable to find the 3.2 tutorial repo to compare my sample_app to but I think I've followed the tutorial to the letter. Any help is appreciated.
Yes, The problem is that you haven't updated your routes. Inside your routes.rb file, you have resources :microposts, only: [:create, :destroy]. The route that its looking for is a :show to :microposts.
Without seeing your controller code, I suspect that after you delete the micropost, you are trying to redirect back to the micropost. Either update your route to this: resources :microposts, only: [:create, :destroy, :show] or post up the details of your microposts controller.
I had the same problem, and after restarting the rails server it worked fine for me.
[posting if anyone visits this page lately]
As I can see the problem is that your delete request goes as 'GET', But as per the REST conversions it should be a 'POST' request,
And I just created a sample app with Rails 3.1.3 and its delete link is as follows
In this case I have created a scaffold called User
<%= link_to 'Destroy', user, :confirm => 'Are you sure?', :method => :delete %>
You can check what is happening to your delete request by using Firebug with Firefox
I am working through the same tutorial, and am having the same problem. My analysis is that the problem is because we are using redirect_back_or root_path in the microposts controller (~/rails_projects/sample_app/app/controllers/microposts_controller.rb):
class MicropostsController < ApplicationController
...
before_filter :correct_user, only: :destroy
...
def destroy
#micropost.destroy
logger.debug "in MicropostsController.destroy:"
logger.debug " root_path=#{root_path}"
logger.debug " session[:return_to]=#{session[:return_to]}"
redirect_back_or root_path
end
The output from the logger.debug statements shown is:
in MicropostsController.destroy:
root_path=/
session[:return_to]=/microposts/28
Recall that redirect_back_or is defined in sessions_helper.rb as:
def redirect_back_or(default)
redirect_to(session[:return_to] || default)
clear_return_to
end
So, the call to redirect_back_or root_path will result in:
redirect_to(/microposts/28)
I'm a newbie here, but I think the default action is GET; at least, that's consistent with what I'm seeing, i.e. this is why we are posting a GET to /microposts/28.
Meanwhile, in routes.rb, we have defined the resource microposts to only support create and destroy actions:
resources :microposts, only: [:create, :destroy]
Of course, we don't want to GET the micropost we just deleted; we want to re-render (or re-direct?) back to the page from which we came. As evidence that this analysis is correct as far as it goes, I found that calling redirect_to root_path instead of redirect_back_or root_path "works", in that the micropost gets deleted (after popup confirmation), and puts the user back on the home page (showing the deleted micropost is gone).
I have now changed my as follows, so that the page from which the delete action was invoked re-appears:
def destroy
#micropost.destroy
redirect_to request.referer
end
I also changed my definition of SessionsHelper#store_location:
def store_location
session[:return_to] = request.fullpath if ['show', 'edit'].include?action_name
end
So, only 'show' and 'edit' actions attempt to resume after login.