Search code examples
ruby-on-railsdevisecontrollerassociationsdestroy

Rails Device and has_many association with promotions privilege


I have two models User and Promotion, an user can create has_many promotion and an promotion belong to user, for the users i used devise so:

when I delete a promotion, I would like that the users can't delete also the promotions of other users but only their own

I have to change the controller but how? i hope in a help

this is controller for the destroy of a promotion

def destroy
@promotion = Promotion.find(params[:id])
@promotion.destroy
#@promotion = current_user.promotions.destroy

respond_to do |format|
  format.html { redirect_to promotions_url, notice:'Promotion was successfully delete.' }
  format.json { head :ok }
 end
 end
end

sorry for my english please!


Solution

  • Crosscheck if the current_user is also the creator of the @promotion:

    def destroy
      @promotion = Promotion.find(params[:id])
      if @promotion.user == current_user #if user is the owner of that promotion
        @promotion.destroy
        respond_to do |format|
          format.html { redirect_to promotions_url, notice:'Promotion was successfully delete.' }
          format.json { head :ok }
        end
      else
        redirect_to root_path
      end
    end