Topic: Major Refactor of Delete Method

New to RoR ...as you can tell wink
So - I haven't even put in the if @post.destroy or if current_user.save. This is why these are displayed in multiple places ... here so undry. So functionally everything is fine here. But I stopped at this point figuring I need major help understanding what's best to do to make this nice and clean.

def delete
    # displays delete template or deletes/cancels after form action
    @post = Post.find(params[:id])
    if params[:commit] == "Delete"
      respond_to do |wants|
        wants.html{
          current_user.post_count -= 1
          @post.destroy
          current_user.save
          flash[:notice] = "you deleted that post baby"
          redirect_to posts_path
        }
        wants.js {
          @post.destroy
          current_user.post_count -= 1
          current_user.save
          render :text => "deleted" # ajax handles removal of div
        }
      end
    elsif params[:commit] == "Cancel"
      respond_to do |wants|
        wants.html{
          redirect_to posts_path
        }
        wants.js{
          render :text => "canceled" # ajax handles close of dialog
        }
      end
    end
  end

Last edited by spherop (2008-09-16 20:14:15)

Re: Major Refactor of Delete Method

You can change the cancel on the client to not submit the form - I generally just use a link for cancel, which also has the effect of signaling to the user that cancel is not operational.

So:

[Delete] or Cancel

Where Delete is a button and Cancel is a text link.


Then factor out the common code for the different responses:

def delete

  @post = Post.find(params[:id])
  current_user.post_count -= 1
  @post.destroy
  current_user.save

  respond_to do |wants|
    wants.html {
      flash[:notice] = "you deleted that post baby"
      redirect_to posts_path
    }
    wants.js { render :text => "deleted" # ajax handles removal of div }
  end
end

Toby Hede
===================================================
FiniteStateMachine - Software Development for Social Networks
===================================================