MKK
MKK

Reputation: 2753

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

Upvotes: 0

Views: 173

Answers (1)

Tigraine
Tigraine

Reputation: 23648

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

Upvotes: 1

Related Questions