1
votes

_user.html.erb

<li>
  <%= gravatar_for user, size: 50 %>
  <%= link_to user.name, user %>
  <% if current_user.admin? && !current_user?(user)%>
    | <%= link_to "delete", user, method: :delete,
                                  data: { confirm: "You sure?" } %>
  <% end %>
</li>

I delete && !current_user?(user) It can work This is my code session_helper.er.html

def current_user
    if (user_id = session[:user_id])
    @current_user ||= User.find_by(id: user_id)
    elsif (user_id = cookies.signed[:user_id])
      user = User.find_by(id: user_id)
      if user && user.authenticated?(cookies[:remember_token])
        log_in user
        @current_user = user
      end
    end
  end
  def current_user?(user)
    user = current_user  
  end
  def logged_in?
    !current_user.nil?
  end
  def log_out
    forget(current_user)
    session.delete(:user_id)
    @current_user = nil
  end

users_contorller

  def index
      @users = User.paginate(page: params[:page], :per_page => 10)
  end
  def new
      @user = User.new
  end
  def create
      @user = User.new(user_params)
      if @user.save
          log_in @user
          flash[:success] = "Welcome to the Sample App!"
          redirect_to @user
      else
          render 'new'
      end
  end
  def edit
      @user = User.find(params[:id])
  end

/## private def user_params params.require(:user).permit(:name, :email, :password, :password_confirmation) end def logged_in_user unless logged_in? store_location flash[:danger] = "please login" redirect_to login_url end
end //## def correct_user @user = User.find(params[:id]) redirect_to(root_path) unless @user == current_user?(@user) end def admin_user redirect_to(root_url) unless current_user.admin? end

Session_controller.html.erb

class SessionController < ApplicationController

  def new
  end
//##
  def create
    user = User.find_by(email: params[:session][:email].downcase)
    if user && user.authenticate(params[:session][:password])
      log_in user
      params[:session][:remember_me] == '1' ? remember(user) : forget(user)
      redirect_back_or user
    else
      flash.now[:danger] = '無效的電子郵件/密碼'
      render 'new'
    end
  end
//##
  def current_user
    @current_user ||= User.find_by(id: session[:user_id])

  end
//##
  def destroy
        log_out if logged_in?
        redirect_to root_url
  end

end

I can't find some error for it and I am a newbie at ruby on rails .

2

2 Answers

1
votes

In your current_user method you should use comparison (==) instead of assignment (=):

def current_user?(user)
  user == current_user
end
1
votes

Change the user login to

<% if current_user.admin? && user_login?(user)%>
  | <%= link_to "delete", user, method: :delete,data: { confirm: "You sure?" } %>
<% end %>

and

def user_login?(user)
  user == current_user
end