Skip to content

Instantly share code, notes, and snippets.

@edspencer
Created January 9, 2009 11:10
Show Gist options
  • Save edspencer/45085 to your computer and use it in GitHub Desktop.
Save edspencer/45085 to your computer and use it in GitHub Desktop.
#using the attr_accessible declaration to whitelist mass-assignable attributes
#this example will only update title and body when performing a Post.new(params[:post]) or @post.update_attributes(params[:post])
#even if params[:post] contains other keys and values (i.e. thread_id will not be overwritten this way)
class Post
belongs_to :thread
attr_accessible :title, :body
end
class PostsController < ApplicationController
def create
@thread = Thread.find(params[:thread_id])
@post = Post.new(params[:post])
@post.thread = @thread #need to manually specify this because of attr_accessible whitelist
if @post.save
flash[:notice] = "Your post has been created"
redirect_to @post
else
render :action => 'new'
end
end
def update
@post = Post.find(params[:id])
if @post.update_attributes(params[:post])
flash[:notice] = "Post successfully updated"
redirect_to @post
else
render :action => 'edit'
end
end
#the following methods don't even need to be defined as they'll just default to rendering the templates
def new
# just renders the views/posts/new.html.erb file
end
def edit
# just renders the views/posts/edit.html.erb file
end
def rarrar
# would render the views/posts/rarrar.html.erb file, if it exists
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment