开发者

admin? doesn't work with Mongo Mapper

开发者 https://www.devze.com 2023-04-12 04:35 出处:网络
I was trying to play with MongoDb and using the Rails Tutorial to create users.I\'m using the Mongo_mapper gem.I have that all set up but I\'m at the point where it seems that ActiveRecord functions/m

I was trying to play with MongoDb and using the Rails Tutorial to create users. I'm using the Mongo_mapper gem. I have that all set up but I'm at the point where it seems that ActiveRecord functions/methods don't seem to work. All my tests work til this point.

I got toggle! to work by adding this to my user model by looking up the toggle source in APIDock

  def toggle!(field)
    send "#{field}=", !self.send("#{field}?")
    save 
  end

But when I try this function to see if the User model boolean of admin

  def admin?
    self.admin
  end

I get this error from my test.

 1) UsersController DELETE 'destroy' as a non-signed-in user should deny access
     Failure/Error: delete :destroy, :id => @user
     NoMethodError:
       undefined meth开发者_高级运维od `admin?' for nil:NilClass
     # ./app/controllers/users_controller.rb:66:in `admin_user'
     # ./spec/controllers/users_controller_spec.rb:253:in `block (4 levels) in <top (required)

Here's what I have for the controller

class UsersController < ApplicationController
  before_filter :authenticate, :only => [:index, :edit, :update]
  before_filter :correct_user, :only => [:edit, :update]
  before_filter :admin_user,   :only => :destroy
.
.
.  

  def destroy
    User.find(params[:id]).destroy
    flash[:success] = "User deleted."
    redirect_to users_path
  end

  private

    def authenticate
      deny_access unless signed_in?
    end

    def correct_user
      @user = User.find(params[:id])
      redirect_to(root_path) unless current_user?(@user)
    end

    def admin_user
      redirect_to(root_path) unless current_user.admin?
    end

But I do get admin access to work with my admin user and I'm able to delete the user.

<li>
    <%= link_to user.name, user %>
    <% if current_user.admin? %>
        <%= link_to "delete", user, :method => :delete, :confirm => "You sure?",
                                    :title => "Delete #{user.name}" %>
    <% end %>
</li>

Any suggestions on how to fix this as I'm stuck on how to get the app to redirect after deleting a user.


Since you dont have a logged in user during that test, current_user is nil, which is exactly the error you are getting.

So you need to handle the case where current_user is nil:

def admin_user
  redirect_to(root_path) unless current_user.try(:admin?)
end

The try method will handle the case where it is called on a nil object. http://api.rubyonrails.org/classes/Object.html#method-i-try

0

精彩评论

暂无评论...
验证码 换一张
取 消