Create Rails migration with values for column

I need to change a reference for a model while updating the value and not allowing this reference to have null values.

I would like to reference Animal to Specie instead of Breed.

I will not remove Breed from this migration so I can keep it until I make sure everything works properly in production and then will run a cleanup.

Here we go:

class AddSpeciesToAnimal < ActiveRecord::Migration[5.2]
  def down
    remove_reference :animals, :specie, foreign_key: true, index: true
  end

  def up
    add_reference :animals, :specie, foreign_key: true, index: true

    Animal.find_each { |animal| animal.update!(specie: animal.breed.specie) }

    change_column_null :animals, :specie_id, false
  end
end

Beware of ActiveAdmin Filters

ActiveAdmin automatically generates filters for any relationships the model belongs_to. This allows us to sort based on these attributes, which can be super useful. But it can also be painful to load if your attribute has more than a few items since Active Admin loads each one into memory which takes quite a long time, especially if you have thousands or even tens of thousands of them stored in your database.

You can turn off filters you don’t need to allow faster loading. To turn off all filters on a resource just addconfig.filters = false  to your ActiveAdmin model.

To remove only a specific filter(s) use remove_filter :filter_name

To keep only a specific filter(s) use filter :filter_name

This explains why my rspec request tests were having no issues since there are not over 30,000 users in my test database!

This post helped me narrow down my slow performance being caused by filters.

This post has super detailed info on how to customize filters.

In My Own Words: Self Invoking Function JS

I have never seen a self invoking function, and today during my shift as a tech coach at Flatiron School a student asked about it, so I had to do some quick learning. It is rather cool, not quite sure how I would apply it to my code yet, but it is a cool feature to see.

Here is the example from the w3schools closures tutorial (because it uses closure too!):

1
2
3
4
5
var add = (function add () {
    var counter = 0;
    console.log(counter)
    return function () {return counter += 1;}
})();

 

With this block of code every time I call add() it ups the counter.

add();
add();
add();

// the counter is now 3

At a quick glance one would think that every time add() is called it sets var counter = 0 and then the inner function adds 1, and then when you call it again the counter is reset to 0 and again added 1. But it keeps incrementing without resetting to 0.

If you look closer, this function is wrapped in a (), and then immediately invoked with a (). (function{})() Hence the term self invoking function. When this function is loaded initially it creates the variable of counter and assigns it 0.

Then when we call add() this goes straight to the inner function, since the outer function is self invoked. In a regular JS function it would be like add()(). Therefore add() never touches the var counter = 0 and does not reset the counter and increments the counter through closure .

That self invoked function can only be read once, and the result of the invoked function gets assigned to that variable so var counter = 0 can not be called again (in the same instance) for when we call add it is returning the result of when add was assigned.

Pretty amazing!

Day 8 of 30 of Codewars – Javascript

I’ve challenged myself to 30 days of codewars, one a day, time myself, and learn how I could have done it better.

Today I did: https://www.codewars.com/kata/calculate-string-rotation/javascript

Time: 20 minutes

What I’ve learnt: Back to string manipulation at codewars!  So I got a lot of tests passing pretty quickly, but to knock out the ones that should be returning -1  took me a few attempts at adding things to my conditional.

Here was my solution:

1
2
3
4
5
function shiftedDiff(first,second){
  var firstLetterPosition = second.indexOf(first[0])
  if (firstLetterPosition === -1 || (first[1] !== second[firstLetterPosition +1] && firstLetterPosition !== first.length-1 ) || (first[first.length - 1] !== second[firstLetterPosition -1] && first !== second && first[1] !== second[0])) return -1
  return firstLetterPosition
}

 

What I learned from other people’s code:

I should have spent 5 more minutes thinking about what the failing condition was, instead of continuously adding conditionals to get my codewars passing. Seriously all I needed is if first.length != second.length… duh!

The way they did this was seriously interesting (thanks Daniel for explaining by the way!). They added up the two strings (of the second), for example in this test where “coffee” was shifted over 2:

shiftedDiff(“coffee”, “eecoff”) => 2

So second + second would be “eecoffeecoff” and checked at what index does the first (“coffee”) show up, and return that number. Amazing thinking!!

I did this similarly but just by looking for the first letter, had I looked for the whole word if it didn’t exist it would know right there.

Looking forward to tomorrow! Hopefully will do this kata before midnight 😉

Day 6 of 30 of Codewars – Javascript

I’ve challenged myself to 30 days of codewars, one a day, time myself, and learn how I could have done it better.

Today I did: https://www.codewars.com/kata/human-readable-time/javascript

Time: 20 minutes

What I’ve learnt: So I know I could have done this with less conditions, but I was more focused today in trying to accomplish this in a timely way. So there was a lot of copy and paste code, just using a bit different math. Maybe I could have created an outer function I could have passed the math into to keep my code DRYer. I’m never sure how much I should be doing to keep these kata cleaner and cleaner. For now focusing on getting through the challenges in a timely way.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
function humanReadable(seconds) {
  const time = {hours: "00", minutes: "00", seconds: "00"}
  function convertSeconds(seconds){
    if(seconds < 60){
      if (seconds < 10) time.seconds = `0${seconds}`
      else time.seconds = seconds
    } else if(seconds < 3600){
      const minutes = Math.floor(parseInt(seconds)/60)
      if (minutes < 10) time.minutes = `0${minutes}`
      else time.minutes = minutes
      convertSeconds(parseInt(seconds) % 60)
    } else {
      const hours = Math.floor(parseInt(seconds)/3600)
      if (hours < 10) time.hours = `0${hours}`
      else time.hours = hours
      convertSeconds(parseInt(seconds) % 3600)
    }
  }
  convertSeconds(seconds)
  return `${time.hours}:${time.minutes}:${time.seconds}`
}

What I learned from other people’s code: OK, so I see people have created that inner function to call 3 times, and did so very elegantly! Than they returned the function call interpolated with the : Truly concise and impressive! Hmm. So maybe I should spend more time refactoring my code. Although I do see that 31 people did that together!! Power of the pairing 🙂

I do see someone here using =~~. I’ve never seen this, and not sure how to look this one up since google is not really allowing me to search for it. Will ask some of my friends what they think!

Have a good one!

Day 5 of 30 of Codewars – Javascript

I’ve challenged myself to 30 days of codewars, one a day, time myself, and learn how I could have done it better.

Today I did: www.codewars.com/r/w4mfhw

Time: 5 minutes

What I’ve learnt: I think this took me longer to read through all the instructions than to accomplish the kata! I could not figure out how to make them dummy components, so I just made them all react components.

This was a rather simple kata, with not much brainwork required.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
const React = require('react');

class Hello extends React.Component {
    render() {
        return <h1>Hello</h1>;    
    }
}

class World extends React.Component {
    render() {
        return <h2>World!</h2>;    
    }
}

class Greet extends React.Component {
    render() {
        return <div><Hello/><World/></div>;    
    }
}

 

What I learned from other people’s code:

I do like how other people created their dummy components by just creating a variable with the component name with a simple anonymous function returning the expected text.

This just shows me how React really is just using the ES6 class features in JS.

And onto the next 🙂

How View Partials Have Saved Me So Much Time

Since having made so many partials to may app upon creation, it has saved me so much time in updating it, that I felt I should take a few minutes that I gained to write a post on how useful it is, so maybe you will utilize this super easy and handy tool.

On my Recipe App that I made on Ruby on Rails, anything that can be used in multiple places were rendered as a partial.

These same lines were rendered on user show pages, recipe show pages, and index pages. In fact my smallest partial was simply an image of a heart!

Aside from all the work in getting my app to work, and function correctly, have links with proper routes and forms that would submit, I would only have to worry about it once, because it was only in my views once — they were using the same partial.

And when I later implemented JavaScript and Jquery and hijacked links and forms, when I did it in one place, it worked on the whole site. It’s tough enough working with AJAX requests and JQuery/Javascript functions, I don’t need the extra work by having to enter many views to make sure classes and ID’s are always correct.

Here is an example of a partial that was used:

Recipe#Show

1
2
3
4
5
6
7
8
9
<%= render 'recipes/recipe_details', recipe: @recipe %>
<div>
<%= render 'comments/list_comments', comments: @recipe.comments if @recipe.comments %>
</div>
<br />
<div id="comments">
Add your comment below! (You must be signed in)
<%= render 'comments/form', comment: @recipe.comments.new, recipe: @recipe%>
</div>

We’ll follow the Recipe Details to recipe_details:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<h1><%= recipe.name %></h1>
<h2><%= recipe.time_in_minutes %> minutes until it's ready | By: <%= link_to recipe.user_name, user_path(recipe.user)%></h2>

<%= render 'favorites/favorited', recipe: recipe%>

<%= render 'ingredients/list_ingredients', recipe: recipe %>

<h4><%= recipe.instructions %></h4>

  <%= link_to "Edit", edit_recipe_path(recipe) if logged_in? && current_user.can_edit?(recipe)%>

  <%= link_to "Delete", recipe_path(recipe), method: :delete if logged_in? && current_user.can_delete?(recipe)%>

Which then pulls in 2 more partials, one for the favorite icon (our smallest partial), and one for ingredients:

favorites/favorited partial:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
<% if current_user && recipe.favorite?(current_user) %>
  <span class="favorites favorited">
    <%= link_to image_tag("heart-red.png"), "#", :data => {:recipe => recipe.id }%>
    
  </span>
<% else %>
  <span class="favorites favorite">
    <%= link_to image_tag("heart.png"), "#", :data => {:recipe => recipe.id }%>
  </span>
<% end %>

ingredients/list_ingredients partial:

1
2
3
4
5
<ul>  
  <% recipe.recipe_ingredients.each do |recipe_ingredient| %>
    <li><%= "#{recipe_ingredient.quantity} #{recipe_ingredient.ingredient.name}" %></li>
  <% end %>
</ul>

I hope this will inspire you to keep making partials as details as necessary!

Copyright Loving to Code 2025
Tech Nerd theme designed by Siteturner