Skip to content

Instantly share code, notes, and snippets.

@Najaf
Last active December 16, 2015 11:58
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Najaf/5431024 to your computer and use it in GitHub Desktop.
Save Najaf/5431024 to your computer and use it in GitHub Desktop.
Quick tip for implementing access control
# So your PicsController probably looks something like this:
class PicsController < ApplicationController
def update
@pic = Pic.find(params[:id])
@pic.update_attributes(params[:pic])
end
end
# You want to change that to this:
class PicsController < ApplicationController
def update
# This bit makes sure you can only update your own images
@pic = current_user.pics.find(params[:id])
@pic.update_attributes(pic_params)
end
def show
@pic = current_user.pics.find(params[:id])
# do rendering stuff
end
def edit
@pic = current_user.pics.find(params[:id])
end
def destroy
current_user.pics.find(params[:id]).destroy
# redirect somewher useful
end
private
def pic_params
# This bit makes sure you whitelist parameters you send to the model
# The list of attributes here should contain as little as possible and
# almost *never* contain a user_id, for real yo.
params[:pic].slice(:title, :caption, :tags, :other, :stuff, :you, :are, :sure, :you, :want, :users, :to, :be, :able, :to, :edit)
end
end
# I'm making the following assumptions though:
# 1. That a User has_many Pics and a Pic belongs_to a User:
class User < ActiveRecord::Base
has_many :pics
end
class Pic < ActiveRecord::Base
belongs_to :user
end
# 2. That you have access to a `current_user` method from somewhere
# You get it for free if you're using devise, or you may have rolled
# your own in ApplicationController or somewhere
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment