Embed ERB Ruby Code in CSS in Rails

Did you know that you can embed erb code into CSS in rails? I just learned it, and its awesome, and simple.

Start by adding the .erb extension to your css file:


Then bam! you can put erb in your css code:

.navbar-brand {
background-image: url(<%= asset_path 'new-logo.png' %>);
background-size: contain;
background-repeat: no-repeat;


Initialize Rails App Databases Using MySQL After Cloning Repository From Github

So I cloned my colleague’s rails app from github and wanted to run it on my machine so I can collaborate on the code.  But I kept getting the error that the database didn’t exist.

ActiveRecord::NoDatabaseError (Unknown database 'owl_development')

First, I checked what database this rails app was using by looking at the database.yml file and found it was using mysql and the mysql2 gem.

So I made sure that I had mysql installed on my system by using homebrew and the brew install mysql command.  Then I tried rake db:migrate and still got the error that the database didn’t exist.

What I had forgotten to do after I cloned the repo was run

rake db:create

to create the databases.  I know this is obvious in hindsight, but I spent like 3 hours searching around until I figured out that’s what I had forgotten.  Hopefully this will save you some time!

partial credit here

Validate Active Model Numbers Greater Than and Less Than

If you have a model and you want to do validation related to numerical values, such as validate a certain number is less than or greater than another, here’s how you can do it.

validates :inventory_qty, :numericality => { greater_than_or_equal_to: 0, less_than: 100 }

Checkout the documentation for more details.

Credit here.

Use jQuery to Animate Background Color

Although CSS keyframes is probably the easiest way to animate the background color of an element on the page, since earlier versions of Internet Explorer (IE < 10) don’t support CSS keyframes, if you need a more widely supported solution, you can do the same thing in jQuery.

To do this, you use the jQuery .animate() function.  The catch is that in order to be able to change colors with this function, you also need to include the jQuery Color plugin.

The way I did this in Rails was to just create a new file under assets/javascripts and called it jquery_color.js. Then copied the code from the plugin into that file.

Ok, now for the actual code. Credit for this goes to StackOverflow user fitorec‘s answer to this question, and this jsfiddle that he wrote.

$(document).ready(function() {
  var animate_loop, colors, i;
  colors = ['#FFB30C', '#58EC00', '#0087EC', '#EEEEEE', '#FF5A00'];
  i = 0;
  animate_loop = function() {
      backgroundColor: colors[i++ % colors.length]
    }, 1500, function() {

This creates a colors array with the colors that you want to animate. Then it calls the .animate() function, passing in the backgroundColor property, and assigning it to one of the colors in the colors array, and iterates i to go through the array. The animate_loop function then calls itself, to create an infinite loop.

Of course if using Rails you can use js2coffee to convert to coffeescript.

Rails Form form_for Objects Reverse Order of Array

This is pretty simple, but I couldn’t figure out how to do it.  Basically I had a view that went through each object in the nested table array, and rendered it.  However, instead of rendering them all in the order they were created from top to bottom on the page, I wanted to render them in reverse order, so the most recent one was at the top of the page.  There might be several ways of doing this, but here is how I finally did it, and its pretty simple. (probably shouldn’t have taken me this long to figure it out, but hopefully you can read this and save some time!)

Here is the original code in the view:

<%= simple_form_for(@lot) do |f| %>
  <strong>Lot Number:</strong> <%= @lot.number %>
  <strong>Item</strong> <%= Item.find(@lot.item_id).number_rev_name %>
  <strong>Inventory Quantity:</strong> <%= @lot.inventory_qty %>

  <-- Here is where I render a partial for each build_lot, which is a 
         has_many, :through join_table -->
  <%= f.simple_fields_for :build_lots,  do |build_lot| %>
    <%= render 'build_lot_fields', :f => build_lot %>
  <% end %>
  <%= f.button :submit, class: 'btn btn-primary' %>
<% end %>

And here is the code from the partial for each build_lot, _build_lot_fields.html.erb

<div class='nested-fields build-lot-fields'>
  <div class='well'>
    <%= f.input :my_build_id, collection: MyBuild.order(:start_date), label_method: :description, value_method: :id, :prompt => 'Choose a Build', selected: MyBuild.where(current: true), input_html: { id: 'build_select'} %>
    <%= f.input :pull_quantity, label: 'Pull Quantity', as: :string %>
    <%= f.label 'Date' %><%= Date.today %><br>
    <%= f.input :employee_id, collection: Employee.order(:first_name), label_method: :first_name, value_method: :id, prompt: "Choose your name" %>

So this simple trick to reverse the order of the build_lots array that is iterated through to render each partial, is to simply add another parameter to the fields_for call (in this case simple_fields_for from the simple_form gem). This second parameter that we add will be the build_lots array reversed. You can find more about the usage of the fields_for method on its documentation page.

But first we need to create this reversed array in the controller. So in the controller (in the function for the view where I want to show the reversed build_lots) I added this line:

@reverseBuildLots = @lot.build_lots.reverse

Then back in the view, I simply change the form_for line like this:

<%= f.simple_fields_for :build_lots, @reverseBuildLots do |build_lot| %>

passing in the @reverseBuildLots parameter, which is an array of build_lots in reverse order that we created in the controller.

Pretty simple, but took me a while to figure out. Hopefully this will save you some time!

credit here

Customize Devise Timeoutable Length of Time Until Auto Sign Out

The Devise gem is awesome and super useful if you have users logging into your app.  It has a built-in feature for making user sessions automatically signed out or logged out after a certain period of time. Devise calls this :timeoutable.  You can easily customize how long until a user is signed out by going to the config/initializers/devise.rb file and editing the config.timeout_in = 30.minutes line.

  # ==> Configuration for :timeoutable
  # The time you want to timeout the user session without activity. After this
  # time the user will be asked for credentials again. Default is 30 minutes.
  config.timeout_in = 30.minutes # EDIT THIS LINE

So in mine I changed it to

config.timeout_in = 5.minutes

while testing.

Let me know if this was helpful!

Rails Generator Error Not Working, Not Creating Files

I had a really weird issue today, but was hard to debug because no actual error was thrown.

I would run the rails g model User and the output in Terminal looked normal, it says it created the files.

Screen Shot 2014-12-10 at 7.36.41 AM

However, when I checked the directory, no files were actually created. This was super frustrating and very weird.

I was able to find an answer from this SO question, although I have no idea why it works or what ‘spring’ is.

I first ran spring stop, then ran my migration, and it worked great.

If anyone knows more about this please share!