Skip to content

Instantly share code, notes, and snippets.

@barangerbenjamin
Created February 1, 2024 20:52
Show Gist options
  • Save barangerbenjamin/829cb0d71ee6ece9d1ac84b60055a36b to your computer and use it in GitHub Desktop.
Save barangerbenjamin/829cb0d71ee6ece9d1ac84b60055a36b to your computer and use it in GitHub Desktop.
require_relative "../views/posts_view"
class PostsController
def initialize
@view = PostsView.new
end
def index
# Ask the model to retrieve all the records
posts = Post.all
# Pass the posts to the view to be displayed
@view.display(posts)
end
def create
# Ask view to ask for title
title = @view.ask_for("title?")
# Ask view to ask for url
url = @view.ask_for("url?")
# Ask model to save post
post = Post.create(title: title, url: url)
end
def update
# Ask the model to retrieve all the records
posts = Post.all
# Pass the posts to the view to be displayed
@view.display(posts)
# Ask for a post id and transform the string response into an integer
post_id = @view.ask_for("id?").to_i
# Ask the model to find the post in the database
post = Post.find(post_id)
# Ask the viez to prompt the user for a new title
new_title = @view.ask_for("new title?")
# Ask the view to prompt the user for a new url
new_url = @view.ask_for("new url?")
# Ask the model to update the record in the database
post.update(title: new_title, url: new_url)
end
def destroy
# Ask the model to retrieve all the records
posts = Post.all
# Pass the posts to the view to be displayed
@view.display(posts)
# Ask for a post id and transform the string response into an integer
post_id = @view.ask_for("id?").to_i
# Ask the model to find the post in the database
post = Post.find(post_id)
# Ask the model to remove this record
post.destroy
end
def upvote
# Ask the model to retrieve all the records
posts = Post.all
# Pass the posts to the view to be displayed
@view.display(posts)
# Ask for a post id and transform the string response into an integer
post_id = @view.ask_for("id?").to_i
# Ask the model to find the post in the database
post = Post.find(post_id)
# Increment the votes by 1
post.update(votes: post.votes + 1)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment