Users are able to edit other users - ruby-on-rails

I know this was asked before but I double check and made sure that the other questions solutions didn't work for me but anyway, Users are able to edit other users. All you gotta do is change the value id in the address bar and it'll sign you directly into the persons account. I need this fixed and to redirect to their edit page. I've tried multiple things with no luck! I'm not using Devise.
Here is my users_controller.rb,
class UsersController < ApplicationController
before_action :set_user, only: [:edit, :update, :destroy]
before_action :correct_user, only: [:edit, ]
after_action :signed_in_after_register, only: :create
def index
#users = User.all
#user = User.find(session[:user_id])
end
def dashboard
#user = User.find(session[:user_id]) unless session[:user_id] == ""
redirect_to login_path, notice: "You're not logged in" unless #user
#posts = #user.posts.order("created_at DESC").limit(3)
#comment = Comment.new
#post = Post.new
end
def newsfeed
#user = User.find(session[:user_id]) unless session[:user_id] == nil
redirect_to login_path, notice: "You're not logged in" unless #user
#posts = #user.posts.order("created_at DESC").limit(3)
end
def nav
#user = User.find(session[:user_id])
end
def posts
#user = User.find(session[:user_id])
#posts = #user.posts
end
def destroy
#user = User.find(session[:user_id]) unless session[:user_id] == ""
redirect_to login_path, notice: "You're not logged in" unless #user
end
def welcome
#user = User.find(params[:user_id]) unless session[:user_id] == ""
redirect_to login_path, notice: "You're not logged in" unless #user
end
def show
#user = User.find(params[:user_id]) unless session[:user_id] == ""
redirect_to login_path, notice: "You're not logged in" unless #user
#posts = #user.posts.order("created_at DESC").limit(3)
#comment = Comment.new
#post = Post.new
end
def new
#user = User.new
#post = Post.new(params[:post_id])
end
def edit
#user = User.find(params[:user_id]) if params[:user_id]
redirect_to #dashboard_path unless #user
end
def create
#user = User.new(user_params)
respond_to do |format|
if #user.save
format.html { redirect_to dashboard_path, notice: 'User was successfully created!' }
format.json { render :profile, status: :created, location: #user }
else
format.html { render :new }
format.json { render json: #user.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if #user.update(user_params)
format.html { redirect_to dashboard_path, notice: 'User was successfully updated.' }
format.json { render :profile, status: :ok, location: #user }
else
format.html { render :edit }
format.json { render json: #user.errors, status: :unprocessable_entity }
end
end
end
def destroy
#user.destroy
respond_to do |format|
format.html { redirect_to users_url, notice: 'User was successfully destroyed.' }
format.json { head :no_content }
end
end
private
def set_user
#user = User.find(params[:id])
end
def correct_user
#user = User.find(params[:id]) unless session[:user_id] == ""
end
def signed_in_after_register
session[:user_id] = #user.id
end
def user_params
params.require(:user).permit(:first_name, :last_name, :bio, :password, :password_confirmation, :email, :age, :profile_picture, :post, :body)
end
end
Not to sure what other code you may need to see with this being a controller issue, If you do need any other code of mine just comment and ill edit my question right away! Thank you in advance!

You can prevent users from editing each other's profiles by implementing a current_user helper method and checking it from within your edit and update method.
Add the following method to app/controllers/application_controller.rb
def current_user
#current_user ||= User.find(session[:user_id]) if session[:user_id]
end
This helper will return a User object representing the current user in any view or controller.
Now in your app/controllers/users_controller.rb, replace your update method with the following:
def update
if #user == current_user
respond_to do |format|
if #user.update(user_params)
format.html { redirect_to dashboard_path, notice: 'User was successfully updated.' }
format.json { render :profile, status: :ok, location: #user }
else
format.html { render :edit }
format.json { render json: #user.errors, status: :unprocessable_entity }
end
end
else
redirect_to some_other_path, notice: 'You do not have permission to edit the profile of another user.'
end
end
You'll also have to set up your users_controller#edit method to use similar logic, but I'll leave that exercise to you, since the point is for you to learn something.

Related

Devise model with CRUD

Problem: when I create.save guest, error appears ActionController::UnknownFormat in GuestsController#create, through the record is saved. Any Ideas how to get rid of it?
I have:
rails g devise guest ;
rails g controller guests for CRUD interface.
guests_controller.rb:
class GuestsController < ApplicationController
before_action :set_guest, only: [:show, :edit, :update, :destroy]
def new
#guest = Guest.new
end
def edit
#guest = Guest.find(params[:id])
end
def create
respond_to do |format|
#guest = Guest.new(guest_params)
if #guest.save
redirect_to guests_path, notice: 'Client was successfully created.'
else
render :new
end
end
end
def update
#update without changing password
if params[:guest][:password].blank?
params[:guest].delete(:password)
params[:guest].delete(:password_confirmation)
end
#usual actions
#guest = Guest.find(params[:id])
if #guest.update_attributes(guest_params)
sign_in(#guest, :bypass => true) if #guest == current_guest
redirect_to guests_path, notice: 'Client was successfully updated.'
else
render :edit
end
end
private
def set_guest
#guest = Guest.find(params[:id])
end
def guest_params
params.require(:guest).permit(:email, :password, :password_confirmation)
end
end
Maybe some redirect in registrations/controller?...
I tried routes devise_for :guests, controllers: { registrations: 'guest_registrations' } + guest_registrations_controller.rb:
class GuestRegistrationsController < Devise::RegistrationsController
protected
def after_sign_up_path_for(guest)
guests_path # Or :prefix_to_your_route
end
end
but it did nothing
You are using respond_to but you are not telling the response format
Try this instead:
def create
respond_to do |format|
format.html do
#guest = Guest.new(guest_params)
if #guest.save
redirect_to guests_path, notice: 'Client was successfully created.'
else
render :new
end
end
end
end
A response format can be :json, :html, :xml, :js.
More better version than above:
def create
respond_to do |format|
#guest = Guest.new(guest_params)
if #guest.save
format.html { redirect_to guests_path, notice: 'Client was successfully created' }
format.json {render json: #guest}
else
format.html { render :new }
format.json { render json: #guest.errors.full_messages, status: :bad_request }
end
end
end

No route matches {:action=>"index", :controller=>"comments", :post_id=>nil} missing required keys: [:post_id]

This is the issue I am having, Haven't been able to get around it. Now this happens while logging into the account. I haven't had this issue before til last night.
Here is my users_controller.rb,
class UsersController < ApplicationController
before_action :set_user, only: [:edit, :update, :destroy]
before_action :correct_user, only: [:edit ]
after_action :signed_in_after_register, only: :create
def index
#users = User.all
#user = User.find(session[:user_id])
if params[:search]
#users = User.search(params[:search]).order("created_at DESC")
else
#users = User.all.order('created_at DESC')
end
end
def dashboard
#user = User.find(session[:user_id]) unless session[:user_id] == ""
redirect_to login_path, notice: "You're not logged in" unless #user
#posts = #user.posts.order("created_at DESC").limit(3)
#comment = Comment.new
#post = Post.new
end
def newsfeed
#user = User.find(session[:user_id]) unless session[:user_id] == nil
redirect_to login_path, notice: "You're not logged in" unless #user
#posts = #user.posts.order("created_at DESC").limit(3)
end
def nav
#user = User.find(session[:user_id])
end
def posts
#user = User.find(session[:user_id])
#posts = #user.posts
end
def destroy
#user = User.find(session[:user_id]) unless session[:user_id] == ""
redirect_to login_path, notice: "You're not logged in" unless #user
end
def welcome
#user = User.find(params[:user_id]) unless session[:user_id] == ""
redirect_to login_path, notice: "You're not logged in" unless #user
#user = User.find(session[:user_id])
end
def show
#user = User.find(params[:user_id]) unless session[:user_id] == ""
redirect_to login_path, notice: "You're not logged in" unless #user
#posts = #user.posts.order("created_at DESC").limit(3)
#comment = Comment.new
#post = Post.new
end
def new
#user = User.new
#post = Post.new(params[:post_id])
end
def edit
#user = User.find(params[:user_id]) if params[:user_id]
redirect_to #dashboard_path unless #user
end
def create
#user = User.new(user_params)
respond_to do |format|
if #user.save
format.html { redirect_to dashboard_path, notice: 'User was successfully created!' }
format.json { render :profile, status: :created, location: #user }
else
format.html { render :new }
format.json { render json: #user.errors, status: :unprocessable_entity }
end
end
end
def update
if #user == current_user
respond_to do |format|
if #user.update(user_params)
format.html { redirect_to dashboard_path, notice: 'User was successfully updated.' }
format.json { render :profile, status: :ok, location: #user }
else
format.html { render :edit }
format.json { render json: #user.errors, status: :unprocessable_entity }
end
end
else
redirect_to dashboard_path, notice: 'You do not have permission to edit the profile of another user.'
end
end
def destroy
#user.destroy
respond_to do |format|
format.html { redirect_to users_url, notice: 'User was successfully destroyed.' }
format.json { head :no_content }
end
end
private
def set_user
#user = User.find(params[:id])
end
def correct_user
#user = User.find(params[:id]) unless session[:user_id] == ""
end
def signed_in_after_register
session[:user_id] = #user.id
end
def user_params
params.require(:user).permit(:first_name, :last_name, :bio, :comments, :password, :password_confirmation, :email, :age, :profile_picture, :post, :body)
end
end
Heres my comments _form.html.erb,
<%= form_for([#post, #comment]) do |f| %>
<p>
<%= f.text_area :body, placeholder: "Write a comment!" %>
</p>
<br>
<p> <%= f.submit %> </p>
<% end %>
And here is my routes.rb,
Rails.application.routes.draw do
root 'welcome#welcome'
get 'login' => 'sessions#login', :as => :login
get 'dashboard' => 'users#dashboard', :as => :dashboard
post 'logging/user' => 'sessions#create'
get 'logout' => 'sessions#destroy', :as => :logout
get 'about' => 'about'
get 'newsfeed' => 'users#newsfeed'
resources :users, except: :show
get 'profile/:user_id' => 'users#show', as: :profile
get 'location' => 'location#location'
resources :posts do
resources :comments
end
get 'index' => 'posts#index'
get 'register' => 'users#new', :as => :register
end
If you guys do need to see anymore code then just let me know, I will post it! Thank you so much in advance!
The problem is you're trying to create a URL that looks like this: /posts/:post_id/comments by passing form_for([#post, #comment]). It's OK that #comment isn't saved to the database, but the #post you use must already be saved to the database because you can't create that URL without #post having an ID.
Once #post is saved, it'll have an ID, so you can generate the route: for example, /posts/32/comments.
Check your dashboard.html.erb file for where you're using #posts and rendering comments/_form.html.erb. You may have a post object available, and you should use it in your form instead: form_for([post, #comment]).
You'll probably also want to remove the #post = Post.new line from your #dashboard controller action.

How to set a users post id to their post

I'm having issues associating a users status post to them, I also can't get it to show on their account.
This is in my users_controller
class UsersController < ApplicationController
before_action :set_user, only: [:show, :edit, :update, :destroy]
after_action :signed_in_after_register, only: :create
def index
#users = User.all
end
def profile
#user = User.find(session[:user_id]) unless session[:user_id] == ""
redirect_to login_path, notice: "You're not logged in" unless #user
#posts = #user.posts
end
def _nav
#user = User.find(session[:user_id])
end
def destroy
#user = User.find(session[:user_id])
end
def welcome
#user = User.find(session[:user_id])
end
def show
#user = Post.first.update_attributes(user_id: 1)
#post = Post.first.update_attributes(#signed_in_user)
end
def new
#post = Post.new(params[:post_id])
#user = User.new
end
def edit
end
def create
#post.user = current.user
#user = User.new(user_params)
respond_to do |format|
if #user.save
format.html { redirect_to profile_path, notice: 'User was successfully created.' }
format.json { render :show, status: :created, location: #user }
else
format.html { render :new }
format.json { render json: #user.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if #user.update(user_params)
format.html { redirect_to #user, notice: 'User was successfully updated.' }
format.json { render :show, status: :ok, location: #user }
else
format.html { render :edit }
format.json { render json: #user.errors, status: :unprocessable_entity }
end
end
end
def destroy
#user.destroy
respond_to do |format|
format.html { redirect_to users_url, notice: 'User was successfully destroyed.' }
format.json { head :no_content }
end
end
private
def set_user
#user = User.find(params[:id])
end
def signed_in_after_register
session[:user_id] = #user.id
end
def user_params
params.require(:user).permit(:name, :password, :password_confirmation, :email, :age, :profile_picture, :post)
end
end
This is in my posts_controller
class PostsController < ApplicationController
def index
#posts = Post.all.order('created_at DESC')
end
def new
#post = Post.new
end
def create
#post = #signed_in_user
#post = Post.new(post_params)
if #post.save
redirect_to #post
else
render 'new'
end
end
def show
#post = Post.find(params[:id])
#signed_in_user = session[:user_id]
end
def edit
#post = Post.find(params[:id])
end
def update
#post = Post.find(params[:id])
if #post.update(params[:post].permit(:body))
redirect_to #post
else
render 'edit'
end
end
def destroy
#post = Post.find(params[:id])
#post.destroy
redirect_to posts_path
end
private
def post_params
params.require(:post).permit(:body)
end
end
This is the profile.html.erb page that I want the signed_in_users most recent post to be returned to
<%- #posts.each do |post| %>
<div class="post_wrapper">
<h2 class="title"><%= link_to post.body, post %></h2>
<p class="date"><%= post.created_at.strftime("%B, %d, %Y") %> </p>
</div>
<% end %>
This is in my routes
Rails.application.routes.draw do
root 'welcome#welcome'
get 'login' => 'sessions#login', :as => :login
get 'profile' => 'users#profile', :as => :profile
post 'logging/user' => 'sessions#create'
get 'logout' => 'sessions#destroy', :as => :logout
get 'about' => 'about'
resources :users
resources :posts
get 'index' => 'posts#index'
get 'register' => 'users#new', :as => :register
Just to clear the question up a bit more and be very specific, I want it to be exactly like a status post that Facebook offers, You write it, It post, It shows on your profile. That's it, I have no problems with Writing, Posting and it saving. It just doesn't show on the profile page of the user that created it.
run this command in your terminal:
rails generate migration AddUserRefToPosts user:references
in your user model:
class User < ActiveRecord::Base
has_many :posts
...
end
3.in post controller
def create
#post = Post.new(post_params)
#post.user_id = #signed_in_user.id
if #post.save
redirect_to #post
else
render 'new'
end
end
Try this
def create
#post = #signed_in_user.posts.build(post_params)
if #post.save
redirect_to #post
else
render 'new'
end
end
Your create action should look like this
def create
#post = Post.new(post_params)
#post.user_id = #signed_in_user.id
if #post.save
redirect_to #post
else
render 'new'
end
end

Add user id to blog post

I have a simple blog application. When posts are added, i want the users id to be added to the post so that when a user is logged in, he can only see his posts. The id i want to add to the post, is the id of the user currently logged in.
How and where could the id attribute be added to the posts model?
Session controller:
class SessionsController < ApplicationController
def new
end
def create
user = User.authenticate(params[:username], params[:password])
if user
session[:user_id] = user.id
redirect_to blog_url, :notice => "Logged in!"
else
flash.now.alert = "Invalid email or password"
render "new"
end
end
def destroy
session[:user_id] = nil
redirect_to root_url, :notice => "Logged out!"
end
end
Application controller:
class ApplicationController < ActionController::Base
protect_from_forgery
before_filter :authenticate
helper_method :current_user
private
def current_user
#current_user ||= User.find(session[:user_id]) if session[:user_id]
end
def authenticate
redirect_to log_in_path unless session != nil
end
end
Posts controller:
class PostsController < ApplicationController
# GET /posts
# GET /posts.json
def index
#posts = Post.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: #posts }
end
end
# GET /posts/1
# GET /posts/1.json
def show
#post = Post.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: #post }
end
end
# GET /posts/new
# GET /posts/new.json
def new
#post = Post.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: #post }
end
end
# GET /posts/1/edit
def edit
#post = Post.find(params[:id])
end
# POST /posts
# POST /posts.json
def create
#post = Post.new(params[:post])
post.user_id = session
respond_to do |format|
if #post.save
format.html { redirect_to #post, notice: 'Post was successfully created.' }
format.json { render json: #post, status: :created, location: #post }
else
format.html { render action: "new" }
format.json { render json: #post.errors, status: :unprocessable_entity }
end
end
end
# PUT /posts/1
# PUT /posts/1.json
def update
#post = Post.find(params[:id])
respond_to do |format|
if #post.update_attributes(params[:post])
format.html { redirect_to #post, notice: 'Post was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: #post.errors, status: :unprocessable_entity }
end
end
end
# DELETE /posts/1
# DELETE /posts/1.json
def destroy
#post = Post.find(params[:id])
#post.destroy
respond_to do |format|
format.html { redirect_to posts_url }
format.json { head :no_content }
end
end
end
Thanks in advance!
In PostsController
def create
#post = current_user.posts.build(params[:post])
...
end

Rails 3: despair - cannot login to successfully created account with Authlogic

I installed Authlogic gem, set up controllers and models. When I make a registration of new account with Authlogic, everything is successfully created in the DB table (like crypted_password, password_salt etc).
The components: UserSessionsController:
# encoding: utf-8
class UserSessionsController < ApplicationController
def new
#user_session = UserSession.new
end
def create
#user_session = UserSession.new(params[:user_session])
respond_to do |format|
if #user_session.save
format.html { redirect_to(root_url, :flash => { success: 'Successfully logged in.'}) }
format.xml { render :xml => #user_session, :status => :created, :location => #user_session }
else
format.html { #render :action => :new
redirect_to :back
flash[:warning] = 'Wrong credentials.'
}
format.xml { render :xml => #user_session.errors, :status => :unprocessable_entity }
end
end
end
def signin
#user_session = UserSession.new
end
def destroy
#user_session = UserSession.find
#user_session.destroy
respond_to do |format|
format.html { redirect_to(root_url, :notice => 'Logged out.') }
format.xml { head :ok }
end
end
end
UsersController
class UsersController < ApplicationController
filter_access_to :all
def index
#users = User.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: #users }
end
end
def show
#user = User.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: #user }
end
end
def signup
#user = User.new
#categories = Category.order('name')
end
def new
#user = User.new
#categories = Category.order('name')
respond_to do |format|
format.html # new.html.erb
format.json { render json: #user }
end
end
def edit
#user = User.find(params[:id])
#categories = Category.order('name')
redirect_to root_url unless current_user.id == #user.id
end
def create
params[:user][:id_code] = User.random_numbers
params[:user][:url_name] = params[:user][:name].parameterize
#user = User.new(params[:user])
respond_to do |format|
if #user.save
Assignment.create(:user_id => #user.id, :role_id => MEMBER)
format.html { redirect_to root_url, notice: 'User was successfully created.' }
format.json { render json: #user, status: :created, location: #user }
else
format.html { render action: "new" }
format.json { render json: #user.errors, status: :unprocessable_entity }
end
end
end
def update
#user = User.find(params[:id])
respond_to do |format|
if #user.update_attributes(params[:user])
format.html { redirect_to #user, notice: 'User was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: #user.errors, status: :unprocessable_entity }
end
end
end
def destroy
#user = User.find(params[:id])
#user.destroy
respond_to do |format|
format.html { redirect_to users_url }
format.json { head :no_content }
end
end
end
application_controller.rb
class ApplicationController < ActionController::Base
protect_from_forgery
before_filter :mailer_set_url_options
before_filter :set_current_user
helper_method :current_user_session, :current_user
def mailer_set_url_options
ActionMailer::Base.default_url_options[:host] = request.host_with_port
end
protected
def set_current_user
Authorization.current_user = current_user
end
private
def current_user_session
logger.debug "ApplicationController::current_user_session"
return #current_user_session if defined?(#current_user_session)
#current_user_session = UserSession.find
end
def current_user
logger.debug "ApplicationController::current_user"
return #current_user if defined?(#current_user)
#current_user = current_user_session && current_user_session.user
end
def authentication
logger.debug "ApplicationController::authentication"
unless current_user
#store_location
flash[:warning] = "You must be logged out to access this page"
redirect_to root_url
return false
end
end
end
user_session.rb
class UserSession < Authlogic::Session::Base
# attr_accessible :data, :sessions_id
generalize_credentials_error_messages "Login info is invalid!"
def to_key
new_record? ? nil : [ self.send(self.class.primary_key) ]
end
self.logout_on_timeout = true
def persisted?
false
end
end
user.rb
class User < ActiveRecord::Base
attr_accessible #list of all columns
acts_as_authentic do |c|
c.login_field = 'email'
c.logged_in_timeout(15.minutes)
end
has_many :assignments
has_many :roles, :through => :assignments
#validates...
# declarative_authentications
def role_symbols
roles.map do |role|
role.name.underscore.to_sym
end
end
end
I am trying to solve this issue already second day, but I still cannot find the problem... In the DB table are all data needed for Authlogic created, but when I try to log in, I always get the error message Wrong credentials..
Could anyone help me, please, with this problem? I already have no idea, how to fix it :/
Ok, problem seems to be solved - I used for my purposes the column name active, which using also Authlogic.
Renamed to activity and everything is working well.

Resources