简体   繁体   中英

How to permit creator to destroy his own record with Devise on Rails3

When the user is logged in, only the user who create the record can destroy his own record. What should I add to the code below??

  def destroy

    @topic = Topic.find(params[:id])
    @topic.destroy
    flash[:notice] = "topic deleted!"

  end

What you are looking for is not really devise but a authorization solution like CanCan .

Devise can only authenticate users and verify that they are logged in and active. What you need is a way to determine if the user has the right to delete this topic or not.

You can of course roll your own like this:

  def destroy
    @topic = Topic.find(params[:id])
    if @topic.user_id == current_user.id
      @topic.destroy
      flash[:notice] = "topic deleted!"
    else
      flash[:error] = "not allowed"
    end
  end

(The code assumes you have a belongs_to :creator, :class_name => :user association set up in your Topic.. But you get the idea).

But using something like CanCan will make your life a whole lot easier and would reduce the code to something like this:

  def destroy
    @topic = Topic.find(params[:id])
    authorize! :destroy, @topic
    @topic.destroy
    flash[:notice] = "topic deleted!"
  end

With your ability file (See defining abilities ) set up like this:

can :manage, Topic, :owner_id => user.id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM