John
John

Reputation: 397

Rails how to implement role and define role's power?

Now, in my rails app, I use simple authentication(email, password) and give account role to define what account can do.

  def login
    email = params[:email]
    @account = Account.find_by_email(email)
    if @account && @account.authenticate(params[:password])
      session[:user_id] = @account.id
      redirect_to books_path
    else
      render :login
    end
  end

def current_user
    @current_user ||= Account.find(session[:user_id]) if session[:user_id]
end

for example: two role manager(role_id:1) and user(role_id:2...N) in controller, I use stupid way to set data for each role like:

every book has account_id

def index
    @books = Book.where("account_id = ?,@current_user.id)
    @books = Book.all if @current_user.role_id == 1
end

it seems so foolish, and I tried to use cancancan to solved this, but as I know, cancancan just can define for Restful method, and can distinguish role authority like manager can do all and method can do show... does cancancan can do some way to solved what role can see what data they own? use cancancan or other way to solved? please give me some advice! thanks.

Upvotes: 1

Views: 55

Answers (1)

rob
rob

Reputation: 2296

you can use the cancancan helper :can? for this

for example

define your abiliies for each role

can :read, Book

now cancancan check if your user with the specific role can read the book entries

or you check it (on other pages) with:

<% if can? :create, Book %>
  .....
<% end %>

you can also define your own abilities see the wiki for detailed help

Upvotes: 3

Related Questions