This entire section and the previous article has been working with the backend of my app. Eventually I will be able to do all of these things from the browser, but for now I need to understand how this works from the backend.
In order to edit an entry in a database, you first need to grab it. You can grab it by assigning it to a variablearticle = Article.find(2)
article.title = "This is the new title of the 2nd article"
article.save
to save the change. If you want to see that change, typeArticle.all
article.destroy
to delete it.
The way our app is currently set up, people can enter blank entries to clog up the app. We don’t want that so we need to set validations at the model layer to maintain data integrity. We want to make sure that all entries have a title and a description. The validation needs to be added to app > models > article.rb. The code should be: class Article < ApplicationRecord
validates :title, presence: true
end
What this does is makes sure that the title of reload!
class Article < ApplicationRecord
validates :title, presence: true, length: { minimum: 3, maximum: 50 }
end
Now if you try to create an article without a title or the title is too short or long, there will be an error when you try to save it using article.save
. If you are curious of what the error is (it doesn’t tell you right off) then you have to type: article.errors.full_messages
and it will tell you what went wrong.
And don’t forget to push changes to git. Use git status
to see what files have changed without having been committed. git add -A
will add those files to a commit. Then use git commit -m "your message"
to actually add the changes to the commit and then use git push
to push the changes.