Class: FormCreation::PostsController

Inherits:
ApplicationController show all
Defined in:
app/controllers/form_creation/posts_controller.rb

Instance Method Summary collapse

Instance Method Details

#createObject

POST method for processing form data



21
22
23
24
25
26
27
28
29
30
# File 'app/controllers/form_creation/posts_controller.rb', line 21

def create   
  @post = Post.new(post_params)
  if @post.save 
    flash[:notice] = 'Post added!'   
    redirect_to posts_path   
  else
    flash[:error] = 'Failed to edit Post!'   
    render :new
  end   
end

#destroyObject

DELETE method for deleting a Post from database based on id



50
51
52
53
54
55
56
57
58
59
# File 'app/controllers/form_creation/posts_controller.rb', line 50

def destroy   
  @post = Post.find(params[:id])   
  if @post.delete   
    flash[:notice] = 'Post deleted!'   
    redirect_to posts_path   
  else   
    flash[:error] = 'Failed to delete this Post!'   
    render :destroy   
  end   
end

#editObject

GET method for editing a Post based on id



33
34
35
# File 'app/controllers/form_creation/posts_controller.rb', line 33

def edit   
  @post = Post.find(params[:id])   
end

#indexObject



5
6
7
8
# File 'app/controllers/form_creation/posts_controller.rb', line 5

def index   
  @posts = Post.order('id DESC')
  @post = Post.new   
end

#newObject

GET method for the new Post form



16
17
18
# File 'app/controllers/form_creation/posts_controller.rb', line 16

def new   
  @post = Post.new   
end

#post_paramsObject

we used strong parameters for the validation of params



62
63
64
# File 'app/controllers/form_creation/posts_controller.rb', line 62

def post_params   
  params.permit(:title, :description, :created_by)   
end

#showObject

GET method to get a Post by id



11
12
13
# File 'app/controllers/form_creation/posts_controller.rb', line 11

def show   
  @post = Post.find(params[:id])   
end

#updateObject

PUT method for updating in database a Post based on id



38
39
40
41
42
43
44
45
46
47
# File 'app/controllers/form_creation/posts_controller.rb', line 38

def update   
  @post = Post.find(params[:id])   
  if @post.update_attributes(post_params)   
    flash[:notice] = 'Post updated!'   
    redirect_to posts_path   
  else   
    flash[:error] = 'Failed to edit Post!'   
    render :edit   
  end   
end