Sorry about the ambiguity for the morning challenge yesterday. Hopefully these instructions clear a few things up for people.
Firstly, run the posts_spec.rb file to insert data into the posts_spec.db database. Use sqlite3 .schema
to ensure you have a table in there.
# CREATE TABLE `posts`
# `id` INTEGER PRIMARY KEY AUTOINCREMENT,
# `title` TEXT,
# `url` TEXT,
# `votes` INTEGER
Now go into your post.rb file.
require 'sqlite3'
DB = SQLite3::Database.new("posts_spec.db")
posts = DB.execute("""
SELECT *
FROM posts
""")
p posts
This code allows you to run SQL in ruby. Posts is an array of posts. Comment out this section when you understand what it's doing.
class Post
def initialize(attributes = {})
# code
end
Add an initialize
method to store instance variables from the posts
table defined above. Use an attributes hash as an argument.
def self.find(id)
# DB.execute( SQL code )
# once you have this working you need to create a new post instance
# Post.new(attributes)
end
Implement a class method find(id)
on the Post
class which takes an integer as an argument (the post id) and will return an instance of Post
.
def self.all
# DB.execute( SQL code )
# once you have this working you need to create a new post instances
# Post.new(attributes)
end
Implement a class method all
on the Post
class which takes no argument and will return an array of Post
instances.
In the end I want you to have a separate file post_test.rb
that looks like this.
require_relative 'post.rb'
Post.find(2)
=> return the instance
Post.all
=> return all instances
Continue on with this challenge and implement ‘destroy’ and ‘save’ instance methods. Think about why these need to be instance methods instead of the class methods we have already made.
This is what I want you to be able to do in your post_test.rb
file.
post = Post.new(title: "Awesome article")
post.id
# => nil (the post is not persisted yet)
post.save # todo: persist the record!
post.id
# => 6 (expected result, the database has inserted a row, store the id in memory)
post.title = "Awesome article, updated"
post.save # todo: should update the record in the database
post.destroy # removes the post from the database