This is the second lab iteration off of Rails Blog Scaffold.
Remember: when you generate models, controllers, etc., be sure to include the --no-test-framework
option so that it skips tests (which the labs already have).
- Add a column to an existing table.
- Generate models, views, and controllers.
- Create associations between models.
- Define proper routes.
- Add validations.
- Change the migration for
posts
to includecontent
(setcontent
's datatype totext
to account for character length). - Create a migration, model and controller for
User
andTag
(viarails generate
). Check out the documentation on generators, and remember to skip adding tests. - In order to create the appropriate associations between
Post
andTag
, we need to create a join table as well. - Build out model associations and migrations.
- Be sure to create the appropriate routes. For now, they can be written as
resources
. create
the database,migrate
the schema, andseed
it.- Make the model association tests pass.
Active Record has handy methods you can place on columns in a table to validate certain attributes, like presence
, length
, and uniqueness
. These are called in a model. Check out the documentation to see more.
Let's add validations to...
Post
for thepresence
of bothname
andcontent
User
for theuniqueness
ofname
Tag
for theuniqueness
ofname
Active Record handles errors when validations aren't met via user input on our forms. Take a look at what's happening in the partial _form.html.erb
for users, which was created when we used Rails's scaffold generator:
<%= form_for(@user) do |f| %>
<% if @user.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@user.errors.count, "error") %> prohibited this user from being saved:</h2>
<ul>
<% @user.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
- Build out the forms for creating a new post.
You've got a great post on kittens that was generated via the seed file, but you want to be able to add some tags. Create a form on the posts form page that lists all the tags as checkboxes, allowing a user to select multiple tags.
Check out the documentation for the collection_check_boxes
form helper here and this post on strong params to be able to make the association between Post and Tag via the Post_Tag join model here.
- Make the tests in
features/tags_for_posts_spec.rb
pass.
View Rails Blog Associations and Validations on Learn.co and start learning to code for free.