Created
August 16, 2013 04:26
-
-
Save joshteng/6247329 to your computer and use it in GitHub Desktop.
Rails 4 way of protecting from mass assignment
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
############### | |
#In Rails 3, we protect attributes that should not be mass assignable by users of the website this way: | |
############### | |
#in the model file: | |
class Post < ActiveRecord::Base | |
attr_accessible :title, :content | |
end | |
#and your controller might look something like that | |
class PostsController < ApplicationController | |
##some other code | |
def create | |
@post = Post.new(params[:post]) | |
if @post.save | |
redirect_to @post | |
else | |
render 'new' | |
end | |
end | |
##some other code | |
end | |
############### | |
#In Rails 4, mass assignment protection is done in the controller file instead! This is done through something called strong parameters. | |
############### | |
#in the model file: | |
class Post < ActiveRecord::Base | |
#the attr_accessible line is no longer here | |
end | |
#instead we place it in the controller file | |
class PostsController < ApplicationController | |
##some code | |
def create | |
@post = Post.new(post_params) | |
if @post.save | |
redirect_to @post | |
else | |
render 'new' | |
end | |
end | |
##some code | |
private | |
##some other code | |
def post_params | |
params.require(:post).permit(:title, :content) | |
end | |
end | |
#Don't worry if your code is not 100% the same. What is important is these few lines: line 41, and 52 to 54. And that attr_accessible is not present in the model. | |
#What happens is that when Post.new(post_params) is being executed, it would invoke the method 'post_params' below and return only the allowed attributes. | |
#and if you are curious what private means, read on. Any methods below private is a private method. Private methods can only be invoked by other methods or code inside this class. Don't worry if you don't understand this yet. | |
#If you are curious about what mass assignment is, read this: http://net.tutsplus.com/tutorials/ruby/mass-assignment-rails-and-you/ | |
#Only read the first 2 parts: (1) What is Mass Assignment? (2) The (Potential) Problem With Mass Assignment | |
#If you choose to read the rest, remember that this was written while Rails 3 was still the default and Rails 4 was still a release candidate. | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment