Class: PostsController

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

Instance Method Summary collapse

Instance Method Details

#createObject

POST method for processing form data



17
18
19
20
21
22
23
24
25
26
# File 'app/controllers/posts_controller.rb', line 17

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

#destroyObject

DELETE method for deleting a Post from database based on id



46
47
48
49
50
51
52
53
54
55
# File 'app/controllers/posts_controller.rb', line 46

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

#editObject

GET method for editing a Post based on id



29
30
31
# File 'app/controllers/posts_controller.rb', line 29

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

#indexObject



2
3
4
# File 'app/controllers/posts_controller.rb', line 2

def index   
  @posts = Post.all   
end

#newObject

GET method for the new Post form



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

def new   
  @post = Post.new   
end

#post_paramsObject

we used strong parameters for the validation of params



58
59
60
# File 'app/controllers/posts_controller.rb', line 58

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

#showObject

GET method to get a Post by id



7
8
9
# File 'app/controllers/posts_controller.rb', line 7

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

#updateObject

PUT method for updating in database a Post based on id



34
35
36
37
38
39
40
41
42
43
# File 'app/controllers/posts_controller.rb', line 34

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