When Upgrading a Rails Application with a new Ruby Version Update Both of These

Today I struggled for a little bit while upgrading the Ruby version of my Rails 6.0 application.

First, I updated the Gemfile and solved a few errors which were caused by that. Unfortunately, I forgot to document these.

The final problem I was having was an inconvience. I change had to change my ruby version in my terminal each time I opened a new terminal tab like this:

rvm use 2.6.5

Setting this each time I changed directory was annoying. The way to ensure it’s set automatically was to change the Ruby version in the .env file.

If you can’t find it via terminal, type

ls -a

in the terminal when you have changed directory into your rails app.

Otherwise, you can find it in the file structure.

how to automatically set what ruby version your rails app uses

Have fun programming!

Deeply Understanding Active Record Associations the Ruby on Rails Way

The purpose of this blog post is to describe Ruby on Rails associations deeply.

Setting up the Practice Environment

First off, I’ll create a new application for practice. I do this on the desktop as it’s an easy place to work from:

rails new association_practice

Next step is to change directories so I’m on the root level of the new application.

cd association_practice

Next, I’ll create an association to practice with. I’m going to start with planet Earth. With Earth as a starting example, I can make associations with most Earthly things.

rails g model Planet name:string

This will generate files for the migration, model, tests and fixtures. I added two planets to the fixture file and a simple test. Which you can see in the following screenshot:

Now that we have the Planet object in our system, I’m going to add the next level of association, the Continent:

rails generate model Continent name:string

This command orders the Rails app to generate four more files. I’ve added to them a little and you can see the changes in the following screenshot:

Ruby on Rails Associations

The goal of this section will be to clearly explain how to use associations to organize your web application’s data.  The association documentation on the Ruby on Rails guides is a good start, but my descriptions below I hope will help deepen your understanding of associations and how to use them.

Understanding belongs_to and has_many Associations

Continents and Planets

Let us create our first association between the continents and the planets. Each continent can belong to a single planet, but a planet can have many continents. Here’s how we assemble it:

Next we migrate the database.

rails db:migrate

Next we load the fixture data.

rails db:fixtures:load

Awesome. Now we have our fixture data loaded and our associations should be set. Here is a screen shot of the actions we can now take in the rails console.

rails c

  1. Here we search the database for a planet with the name Earth. That gives us an array with the matching result in it. We use the .first method to pull the first object. We assign this object to the variable name earth.
  2. Here we use our earth variable to get the name string data which contains the name of the planet (“Earth”).
  3. Here we list the continents associated with earth.
  4. Here we set antarctica variable to equal the continent object of our first continent, Antarctica.
  5. Here we ask the database, “What planet is associated with Antarctica?” It returns us the earth planet object. Notice that the Planet earth object has the same id at the bottom as the Earth at the top.

Work in Progress

I’m thinking of better ways to describe associations. I plan to deep my understanding of the following associations in the future:

  • has_one Association
  • has_many :through Association
    • I’m thinking of describing this by using International Organizations
  • has_one :through Association
  • has_and_belongs_to_many Association
    • I’m thinking of describing this by using members of NATO
  • Choosing Between belongs_to and has_one
  • Choosing Between has_many :through and has_and_belongs_to_many
  • Polymorphic Associations
  • Self Joins

How to get the Last 15th of the Month Using Ruby

How do we compare date times from now against the 15th of last month?

how to make conditional statements since the 15th of last month

I’m  writing a program which assigns episodes to invoices based on the time the episodes were created. Each episode’s publishing date is recorded as follows:

pry(main)> most_recent_episode_publishing_date = Episode.last.updated_at
Episode Load (0.6ms) SELECT "episodes".* FROM "episodes" ORDER BY "episodes"."id" DESC LIMIT $1 [["LIMIT", 1]]
=> Mon, 26 May 2014 18:23:36 UTC +00:00

The above code tells us that the last episode was published on May 26th, 2014.

We save that date object which we can compare against the 15th of the previous month. First we need to get a date object for the day of the 15th of the previous month. Here’s how we do that:

pry(main)> now = Time.now
=> 2019-10-28 13:05:17 -0700
pry(main)> the_15th_of_last_month = Date.new(now.year, now.month, 15).prev_month
=> Sun, 15 Sep 2019

Now that we have the 15th of last month saved as the_15th_of_last_month and the most_recent_episode_publishing_date, we can compare them to know if this episodes is more recent than the last 15th of the month:

pry(main)> most_recent_episode_publishing_date > the_15th_of_last_month
=> false

This means that our most most_recent_episode_publishing_date was published before the 15th of last month. As I only want episodes published in between the last 15th and today, I’ll not add this to the Invoice association.

The logic can be flipped around however you want to use this tool. Enjoy!

Fixing “Single arity template handlers are deprecated” error when upgrading from Rails 5.2 to Rails 6.0

DEPRECATION WARNING: Single arity template handlers are deprecated. Template handlers must
now accept two parameters, the view object and the source for the view object.
Change:
  >> Coffee::Rails::TemplateHandler.call(template)
To:
  >> Coffee::Rails::TemplateHandler.call(template, source)
 (called from at /Users/MediocreManta/Desktop/freedom_podcasting/Rakefile:6)

This was an error I encountered while upgrading my application from Rails 5.2 to Rails 6.0. I found the fix on this Github page, but I thought I’d write it out here to make it a bit clearer for the young programmers out there.

To fix it, I upgraded the coffee-rails by doing the following:

  • Open Gemfile
  • Change gem 'coffee-rails', '~> 4.2'` to `gem 'coffee-rails', '~> 5.0.0'
  • Stop server in terminal by pressing ctrl + s
  • Running the command bundle
  • Restarting the server with rails s

Hope this helps!

I’ve added some language to the Rails documentation via this PR. Hopefully the powers that be accept the addition so future generations can skip having to look this up.

Comma Separated List of Array – Good idea for Ruby on Rails?

I feel like there should be a rails function for doing a comma separated list from an array. Here’s how to do it explicitly:

<% search_tags.each_with_index do |tag, index| %>
  <% if index < search_tags.size - 1 %>
    <%= "#{tag}, " %>
  <% else %>
    <%= "#{tag}" %>
  <% end %>
<% end %>

…maybe `render_comma_separated_list(array)` or something.

An example array would like this = [“one”, “two”, “three”]

render_comma_separated_list(array)

=> one, two, three

Does something like this exist already?

Is this worth the effort of making a PR to Ruby on Rails?

Understanding Polymorphic Associations in Rails

When first trying to get an understanding of polymorphic associations in Rails, I was completely lost. At this point in my learning curve, polymorphic associations are a high-level concept in Rails which allows the programmer to reuse a single model to be useful for other models. It’s difficult to describe without an example. So… here we go.

An example of a polymorphic association is as follows. Let’s say you’re building a sports history database. Baseball players and basketball players are both athletes, but you want to be able to keep the baseballers separate from the basketballers. One way to do that is to create an Athletes model.

The Athlete model would be a way to tie the sports together.

Coding The Polymorphic Association

This requires a migration where we connect the athletes with the sports they play:

rails g migration AddSportToAthlete sport_id:integer sport_type:string

First we set the polymorphic association model:

class Athlete < ApplicationRecord
  belongs_to :sport, polymorphic: true
end

Then we assign that association to the baseballers and the basketballers:

class Baseballer < ApplicationRecord
  has_many :athletes, as: :sport
end

class Basketballer < ApplicationRecord
  has_many :athletes, as: :sport
end

Seeing a Rails App Develop From Looking at Git Changes

I’m deep diving into Ruby on Rails this week. One of the things I find interesting is how the scaffolding creates new parts of a Rails app. This is a helpful tool for understanding the stack so I’m stepping through it looking at the changes made which we can see better with git.

Below is a step by step view of the files created when developing a new Rails App. 

Stepping Through Rails and Watching Git Changes

rails new appName

  • git status => All code related to Ruby on Rails

appName => bundle update

  • git status => No changes

appName => bundle install

  • git status => No changes

appName => bin/rails generate controller name_of_controller

  • git status =>
    • app/assets/javascripts/ian.coffee
    • app/assets/stylesheets/ian.scss
    • app/controllers/ian_controller.rb
    • app/helpers/ian_helper.rb
    • test/controllers/ian_controller_test.rb

Note: git changes do NOT note that when generating a new controller, Rails also generates an empty views folder. This is an important thing to be aware of as your view templates will go here related to your new controller.

appName => bin/rails generate model name_of_model title:string body:text slug:string

  • git status =>
    • app/models/tree.rb
    • db/migrate/
    • test/fixtures/trees.yml
    • test/models/tree_test.rb

Creates the new files needed to maintain a model, it’s test data and test process.

appName => bin/rails db:migrate

  • git status =>
    • db/schema.rb

This process specifically reflects your new model’s functionality with the database.