Ruby on Rails – edit/delete entries & validations

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), where 2 is the article’s ID.  Then all you have to do is typearticle.title = "This is the new title of the 2nd article", then type: article.save to save the change.  If you want to see that change, typeArticle.all.  If you want to delete an entry, grab the article just like we did before, and then type: 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 an entry has a value.  If it doesn’t, then it won’t be allowed to be submitted to the database.  In order for this to work, you do have to restart the rails console so make sure to exit it and restart it before you try.  You can also type reload! to restart the console.  One more constraint we want to add on is to make sure it has a minimum of 3 characters and a maximum of 50 (we don’t want a letter or an entire paragraph as a title…) So the additional code is:
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.