Create Migration in Rails to Improve Lesson Model

Notes


In this lesson we will be making adding an attribute to our Lesson model object. We could use an index on our Lesson model object so that we can easily keep them in order. Also, it might be nice to alter a lesson's availability based on whether or not a user is signed up or not. To do this we need to create a database migration. As usual, we can use the rails generate command to create this for us.

rails g migration AddFieldsToLessons index:integer availability:string

Heading over to our applications root/db/migrations directory we can see the newly created migration file. Remember, in our rails generate command the index and availability are the attribute names and the integer and string are the data types we can expect for the given attribute. Let's migrate our database so our application registers the changes.

rake db:migrate

The next thing we need to do is tell our application's Admin::LessonsController that it can accept the new attributes as parameters. Remember, we explicitly declare what parameters we accept in Rails with strong parameters. Hop down to the lesson_params method and change it like so:

params.require(:lesson).permit(:title, :content, :video_html, :unit_id, :video, :index, :availability)

Also, we need to make it possible to include the new attributes in our form. Let's visit the partial file and copy the form HTML structure for a few more fields.

<div class="form-group">
   <%= form.label :index %>
   <%= form.text_field :index, class: 'form-control %> 
</div>

<div class="form-group">
   <%= form.label :index %>
   <%= form.text_field :index, class: 'form-control %>
</div>

Go ahead and try to create or edit a lesson with an index and availability. Now we will be able to add logic based on these attributes. For example, don't let a user see a lesson if they aren't signed up or make sure the lessons are in order when displayed.

Happy coding!!!!