Life Is Short. Code Hard.

Day 56 of Flatiron School

Seth

2 minute read

life has no ctrl+z

So that intense lab I was talking about yesterday… it took no time at all because of Rails. It was AWESOME. One of the things I learned today that is going to make life easier and ensure DRY.

# example_controller.rb

# Insert at top of controller
before_action :set_example, only: [:show, :edit, :update, :destroy]

# Insert at end of controller
private

def set_example
  @example = Example.find(params[:id])
end

So up until now to access a db object as an instance variable I’ve used the ID passed in from the URL or form and then done a lookup to set the instance variable. That means my code was exactly the same and in four different methods. I always thought this was clunky but didn’t look too hard into how to change it. Now I have a way. So before_action is telling the controller before the action (method) happens do this. However, only: for these [:show, :edit, :update, :destroy] actions. What do we need to do? That’s right, the :set_example action which is then accessible to the listed actions. So the instance variable is available for each of those views. Check out Filter on Rails Guides.

I also learned the difference between PATCH and PUT:

  • PUT has the ability to update the entire object.
  • PATCH updates only the elements that were changed. Therefore this is the preferred method because of lower overhead.

I realize it has only been 4 days since I started Rails but I like taking a snapshot of where I am and where I want to be on Sunday nights. According to my dashboard I’m 32% ( 37 / 113 ) done with Rails. I must’ve counted wrong or things have been added because I counted 104 total plus 3 projects. Either way, I think I’m well on my way to hitting the projects starting May 10th which would take a <5 lessons/day pace.

Okay, I have my Sinatra Project review at 7:15am so I’m off to bed.

Time spent today: 3:52
Time spent total: 213:43
Lessons completed today: 12
Lessons completed total: 443

comments powered by Disqus