Partials of Collections? They’re Awesome.

Partials are coming together more and I have to say they’re pretty sweet. Rails does some automagical stuff that I can’t completely wrap my head around just yet. However, I probably won’t be able to for a while as the people who created it are WAY smarter than me. However, as an example there’s this sequence of things that Rails does:

<% @posts.each do |post| %>
  <%= render :partial => "post", {:locals => {:post => post}} %>
<% end %>

<!-- OR -->

<%= render :partial => "post", :collection => @posts %>

<!-- OR -->

<%= render @posts %>

<!-- Rendering an empty Collection -->

<%= render(@posts) || "There are no blog posts!" %>

The craziest part to me is this little bit that I was taught about <%= render @posts %> which I have bolded for emphasis:

This approach is a bit more abstract. Under the hood, Rails uses the convention that you will have a partial with the name of the models in the collection. Rails will even render a collection of heterogeneous models ([customer, order, customer]) calling the correct partial for each one.

*Mind Blown*

I also took part in a virtual stand up yesterday morning. The instructor who led it asked me if I felt I was retaining the information with the pace I’ve been going (~5 lessons/labs/lectures per day). At the time I said yes because I felt my short days balanced my long days. However, as I worked through some stuff tonight I think my notes are really helping. Pages like this:

are awesome for me to cement more abstract things as well as provide a quick reference to go back and look at when I need. As I work through the curriculum I’m going to see which notes are truly valuable and get them migrated over to my Code & Quill book for long-term reference.

I <3 the community at Flatiron. Here’s a recent chat thread:

jilustrisimo [08:56]
Has anyone been able to roll out Facebook and/or Google OAuth (via Devise) with > an app they’ve deployed to heroku?

yechielk [08:58]
I’ve done github oath

yechielk [08:58]
Make sure you change the app’s URL with Facebook/Google

jilustrisimo [13 hours ago]
[yechielk]2: hey! Do you have any documentation, I’ve been searching on heroku but its either beyond me or not what I’m looking for…I’m not sure where to even place my app_ids/secrets

yechielk [13 hours ago]
Oh, that…

jilustrisimo [13 hours ago]
sigh…yea

zac-baston [13 hours ago]
https://devcenter.heroku.com/articles/config-vars (edited)

yechielk [13 hours ago]
I used a gem called figaro

yechielk [13 hours ago]
https://github.com/laserlemon/figaro
GitHub
laserlemon/figaro
figaro – Simple Rails app configuration

yechielk [13 hours ago]
It’s for storing env variables but it has great heroku integration built in

zac-baston [13 hours ago]
figaro is a good option. also could check out dotenv gem (https://github.com/bkeepers/dotenv) (edited)

jilustrisimo [13 hours ago]
thanks @zac-baston Ill check it out. @yechielk I could never figure out figaro, I used dotenv

jilustrisimo [13 hours ago]
I get using dotenv but arent those files not supposed to be pushed up anywhere?

smithwebtek [13 hours ago]
Yes 2nd the reminder about URL pointing back to Heroku (production). http://diet-planner-v8.herokuapp.com/users/sign_in

zac-baston [13 hours ago]
you certainly shouldn’t commit them to version control. looking at the documentation in that Readme from the repo, it has a section on production in which it recommends the heroku config methods

jilustrisimo [13 hours ago]
thanks guys, I’ll read the doc and shout again if I break everything

snsavage [13 hours ago]
In your Heroku dashboard go to settings and click on Reveal Config Vars. Those keys and values should reflect your .env file.

jilustrisimo [13 hours ago]
@snsavage thanks, I think thats what the doc @zac-baston linked was pointing me towards…so theoretically just set them there then do whatever I need to do for the callbacks?

snsavage [13 hours ago]
So if you’re using something like dotenv you just need to set the values in the dashboard. Just keep the keys the same as your dotenv file.

jilustrisimo [13 hours ago]
do I need to do anything regarding the redirect on FB and Google?

snsavage [13 hours ago]
For my Rails app I have the Facebook site url set to https://carbtracker.herokuapp.com/.

snsavage [13 hours ago]
And then the callback path is handled by OAuth and route.rb as devise_for :users, controllers: { omniauth_callbacks: ‘users/omniauth_callbacks’ }

jilustrisimo [13 hours ago]
it works! at least for Google. I didnt do FB yet

snsavage [13 hours ago]
Great!

jilustrisimo [13 hours ago]
thanks @snsavage @zac-baston @yechielk @smithwebtek !!

yechielk [13 hours ago]
:thumbsup:

zac-baston [13 hours ago]
pretty cool stuff about the web interface. I didn’t know that was there.

jilustrisimo [12 hours ago]
I think its new

jilustrisimo [12 hours ago]
fairly new

snsavage [12 hours ago]
It’s been there since at least 2015.

snsavage [12 hours ago]
It’s hard to find if you don’t know where to look.

sethalexander [3 minutes ago]
I need to save this entire thread for later…

Well, I guess I now saved the entire thread for later…

Time spent today: 2:17
Time spent total: 246:43
Lessons completed today: 4
Lessons completed total: 474

I Partially Understand Partials

I don’t know why I thought Rails layouts and templates would be somewhat easy. While in a sense it’s taking snippets and putting them in other files to reuse of course there has to be some logic in there to ensure that the proper data is being shown. So rendering partials with locals is starting to make sense.

For my example <%= render partial: "authors/author", locals: {author: @author} %>
– The first key-value pair partial: "authors/author" tells Rails the name of the partial to render. Nothing too complex here.
– In the second key-value pair locals: {author: @author} the nested hash {author: @author} key is the name of the variable and its value is the value you’d like it to have in the partial.

I pretty much understand this except for the nested hash’s key. It’ll click I’m sure. I need to get into the Rails console and play some. I have figured out that to effectively have a partial inside a loop I need the argument I pass to the block (the piece in between the |pipes|) the same as the nested hash value. In this case @author.

I’m thinking about presenting a general overview of MVC to my Free Code Camp meetup this weekend. Since I’m basically not thinking about JS at all right now I want to contribute in a meaningful way somehow. Depending on how long that presentation is I might add REST to it. Both MVC & REST are language agnostic so it’ll be useful. Maybe even add CRUD for a 30,000 feet overview of some of the big acronyms in web development.

Time spent today: 2:12
Time spent total: 244:26
Lessons completed today: 4
Lessons completed total: 470

The Pieces Are Coming Together

Feeling great about today. The things that a struggled with the most I ended up cementing (it’s not dry yet) into my brain. The Learn community is awesome I must say. After 2 hours with a Learn Expert (basically a TA), we were both sufficiently stumped. I dropped a note into the student’s Slack channel and <20 minutes it was figured out by the group. So you’re probably wondering what it was…

<h1><%= @post.title %></h1>
<p>
  <%= @post.content %>
</p>
<% @post.categories.each do |c| %>
  <h3><%= c.name %></h3>
<% end %>
<% @post.comments.each do |c| %>
  <p><%= c.user.username %> says: <%= c.content %></p>
<% end %>
<% @post.users.uniq.each do |u| %>
  <%= link_to u.username, user_path(u) %>
<% end %>
<%= form_for @comment do |f| %>
  <%= f.label :content %><br />
  <%= f.text_area :content %><br />
  <%= f.collection_select :user_id, User.all, :id, :username, include_blank: true %><br />
  <%= fields_for :comment_user_attributes, User.new do |u_fields| %>
    <%= u_fields.text_field :username %>
  <% end %><br />
  <%= hidden_field_tag 'comment[post_id]', @post.id %>
<%= f.submit %>
<% end %>

Yeah, it’s in that code… can you find it??? Well, I wrote it and I couldn’t find it so if you can’t all good. If you’re still trying don’t scroll down lol. Here’s the fix with just the line of code that had the error:

<%= f.fields_for :user_attributes, User.new do |u_fields| %>

Yeah, I was missing the f. before fields_for which makes a BIG difference. I can confidently say that I’ll most likely never make that mistake again. I also started taking screenshots during lecture videos of things I wanted to remember and write down. Figured this would be more effective than writing down the time in the video things happen. Although, I did write down a couple larger concepts if I ever need to go back and look.

Something I was struggling with early was collection_select(:post, :author_id, Author.all, :id, :name_with_initial, prompt: true) and reading the APIdock didn’t help. To the Slack channel for people doing Rails I went. Got some solid info. Then later in a lecture video, Avi goes through an almost identical line of code and what it means. Here’s what I got (saved as a screenshot that I’ll write out by hand in my notebook later):

For context higher up in the code: <%= form_for @post do |f| %>
<%= f.collection_check_boxes(:category_ids, Category.all, :id, :name) %>
Will generate a checkbox named post[category_ids][] for each category in Category and it will use the :id as the value for the checkbox and it will use the :name method as the label for the checkbox.

Exactly what I was looking for was right around the corner when I finished the lab. This isn’t the first time I’ve experienced this. There have been many a lecture where after I struggled through something it all became clearer. Specific topics that I had questions about were explained in a way that answered my questions.

Side note, I’ve realized I need something to rest my wrists on. Especially my right hand that uses the mouse. This Microsoft Natural Keyboard has a nice soft wrist rest. However, these 10 hour coding days + this time writing the blog takes a toll.

It’s time for my Sunday night look into where I’m at. I’m 53% done with Rails according to my dashboard and 50 lessons from my Rails projects. I’m still on pace to start my projects on May 10th at a 5 lesson/lab/lecture per day pace. Mon, Thurs & Fri of this past week I spent <1:30 working so if I can get that back up over 2 on weekdays (closer to 3 ideally) and keep this solid 10 on the weekends I’ll be happy.

Time spent today: 10:11
Time spent total: 242:14
Lessons completed today: 9
Lessons completed total: 466

Get in Flow and Go

It felt so good to spend almost the entire day coding. I missed it. My progress was VERY SLOW at times (or so it felt). Things like the :source option in Active Record were foreign and not really taught but needed to solve a large lab I was working on starting first thing this morning. Luckily I have access to some awesome help. Here’s one conversation I had today:

Seth Alexander 34 MINUTES AGO
Need some help understanding the has_many option :source

PJ 34 MINUTES AGO
Hey there Seth how’s it gong?

Seth Alexander 34 MINUTES AGO
Pretty good.

Seth Alexander 33 MINUTES AGO
So in the User model for this lab I get a test passing using:

Seth Alexander 33 MINUTES AGO

has_many :trip_listings, :through => :trips, :source => :listing
has_many :hosts, :through => :trip_listings, :foreign_key => 'host_id'

Seth Alexander 32 MINUTES AGO
I’ve read the Rails Guide and Googled but still don’t grasp what is actually happening when I use :source

Seth Alexander 32 MINUTES AGO
If you could walk me through step by step what my code is doing, that’s what I’m looking for.

PJ 24 MINUTES AGO
Definitely it’s a pretty new topic give me one sec though sorry about hte wait!

Seth Alexander 23 MINUTES AGO
No problem, I’m not actually stuck, just trying to understand better.

PJ 19 MINUTES AGO
no worries! so the idea behind source is pretty fundamental to polymorphic associations – having one object that can be used as essentially a different object with the same properties

PJ 17 MINUTES AGO
an easy example to think about is a family tree – instead of making a new object for every single member of the family you could have one Person class

PJ 15 MINUTES AGO
and then have different associations using the same source object

PJ 13 MINUTES AGO
in this situation you have a User that has listings but since they’re not their own listings (think property manager) but as a guest they namespace them as a trip_listing

Seth Alexander 10 MINUTES AGO
So are we basically “reaching” into trips and pulling out the listing method then setting it to trip_listings for the User model?

PJ 9 MINUTES AGO
well listing is an object so not as much reach for it’s method as reaching for it’s relationship to the object

PJ 9 MINUTES AGO
which since user has many trips it also has whatever relationships come with it

PJ 8 MINUTES AGO
which is sort of the argument against using OO programming because when you have an object with relationships all of a sudden you have everything that it has

PJ 7 MINUTES AGO
there’s a saying that goes “I wanted a banana and you gave me a gorilla in the jungle holding a banana”

Seth Alexander 7 MINUTES AGO
So trip_listings is setting up an association between User and listing > objects for the trips it has many of.

PJ 6 MINUTES AGO
between User as a guest

PJ 6 MINUTES AGO
but yes that’s correct!

Seth Alexander 4 MINUTES AGO
Okay, I guess I was thinking too much about the methods that got enabled and not the whole scope of things. Like, User.trip_listings == User.trips.listings and not the broader picture.

PJ 2 MINUTES AGO
no worries!

Besides the lab that took me about 6 hours I moved along through the material. I had another block where some help was needed and it happened to be that I had one work mixed up. Took about 30 mins to find but once it was found the entire lab worked. It was awesome. The quantity of lessons & labs I’m completely daily is definitely going down lately but the bites are getting larger too. I hope to pick the pace back up (hours in code that is) and get back to where I was when I started. I think I’ll feel better about my progress if I’m at that pace again. It also feels good to get stuff done and see more progress.

Time spent today: 9:40
Time spent total: 232:07
Lessons completed today: 7
Lessons completed total: 457

Coding While Sleeping. Is That Possible?

I’m going to be very happy to code during the day tomorrow. I’ve been tired these last few nights during my target of 8pm – 11pm coding time. I just took a second, leaned back in my chair so my head could rest on the chair back, closed my eyes to think about a problem, and almost fell asleep.

Learned about some Active Record Callbacks of which there are many more than I would have imagined:

  1. Creating an Object
    • before_validation
    • after_validation
    • before_save
    • around_save
    • before_create
    • around_create
    • after_create
    • after_save
    • after_commit/after_rollback
  2. Updating an Object
    • before_validation
    • after_validation
    • before_save
    • around_save
    • before_update
    • around_update
    • after_update
    • after_save
    • after_commit/after_rollback
  3. Destroying an Object
    • before_destroy
    • around_destroy
    • after_destroy
    • after_commit/after_rollback

That’s all. Goodnight.

Time spent today: 0:56
Time spent total: 222:27
Lessons completed today: 1
Lessons completed total: 450

Demo Day & Join the FBI?

I’m exhausted tonight. Been working mainly on more Active Record Associations. More complex ones than before I would assume to get in practice for later labs. Foreign key and Class Name Active Record class methods to be exact if you’re looking for some light reading lol.

I attended an Alumni career fair at my alma mater Belmont University today which was interesting. I never attended one as an undergrad so the whole, drop your resume off on as many tables as possible, was lost on me. I did get a chance to chat with more than a few HR people and get some leads. Nobody was actively hiring Junior Developers but I’m not job ready yet so that’s fine. I’m getting on the radar and will follow up with all of them tomorrow when I can actually type without errors. Also, the FBI recruiter informed me I should apply to be an Intelligence Analyst.

The more fun thing I did today was attend The Iron Yard‘s Spring Demo Day for their current graduating class. It was fun to see people’s projects and learn more about how they built them. I saw some neat stuff. It was also interesting how The Iron Yard splits their students into Front End and Back End tracks then have them work together on their final projects. A few of the guys I met said they might attend the FCC meetup on May 6th so I look forward to that.

Time spent today: 1:30
Time spent total: 221:31
Lessons completed today: 2
Lessons completed total: 449

Don’t Forget to Check the Password

Watching Avi build out the TodoMVC is an interesting thing and I’m happy I get to do it as part of my curriculum and showing what Rails does. That was the bulk of the new work I did tonight. Something that I ran into during my Sinatra project was getting all my associations to work properly. I had issues because of what I now know is called the Active Record Inflector. Now I have this handy table in my notebook:

Name Data
Model Author
Table authors
Foreign Key author_id
belongs_to :author
has_many :authors

This is going to make life easier, although, I’m pretty sure I’ll be building most of my migrations using generators in Rails. However, I’ll still have to fill in my models so this works as a helper for sure.

So… I went to a meetup tonight. I pretty loose one where we all just hung out and worked on whatever we needed to. I decided to work on making my Sinatra portfolio project even better. The largest thing I realized was that I hadn’t implemented authentication checking when people log in. So, I was checking that the username matched one in the db but I wasn’t checking to make sure the password was correct.

post '/login' do
  @user = User.find_by(username: params[:username])
  if !!@user
    session[:id] = @user[:id]
    redirect 'houses'
  else
   redirect 'login'
 end
end

So I added that in 🙂

post '/login' do
  @user = User.find_by(username: params[:username])
  if @user && @user.authenticate(params[:password])
    session[:id] = @user[:id]
    redirect 'houses'
  else
   erb :'users/login'
 end
end

I also realized that this will not give me any errors when the password is incorrect. At least not in the @user.errors way that I was getting errors due to validations not passing. I had to figure out a way to display a username/password is the incorrect message but only when the login fails. I solved that in the view.

<h1>Please Login:</h1>
<p>
  <% if !!@user %>
    <h3 style="color:red">Incorrect username or password.</h3>
  <% end %>
</p>

I still have some UX things to add in so navigation is easier from page to page instead of all of it happening for the most part from dropdowns in the navbar but I’m pretty happy with where the app is at now for being in my portfolio.

Time spent today: 2:59
Time spent total: 220:01
Lessons completed today: 2
Lessons completed total: 447