Sorting a table using calculated model values in Ruby on Rails

Working on a rails project, I created a very simple table to display key information about some customers.  Some of the information are straight from the database columns, such as names and email addresses.  In addition, there are couple of calculated columns, such as total number of transactions per person.  These calculated amounts are methods within the customer model.

secured payday loans online

My next goal was to enable the ability to sort each column in my view table by clicking on the column header.  Ryan Bates has a great screencast on how to do this for fields that match the database column name.  You simply turn the text of each <th> into a link with a “sort” parameter that matches the database column name.  Then, you modify your controller to take in that parameter using the order method of whichever model you are calling.

Unfortunately, that wasn’t enough to help me sort by my calculated fields, like total_transactions.

As I dug around on Google, I found a forum post answered by Ryan Bates (the same Ryan.)  This was very helpful in understanding how to sort using a calculated field:

Customer.find(:all).sort_by { |customer| customer.total_transactions }

However, there was still a piece missing: how to incorporate that into the example he presented in his Railscast. For this, I took a guess of my own.  It works, though I won’t claim it’s the best way to solve the problem.

Anyway, I basically added a second parameter named “type” to the <th> links.  For the static column names, I set

:type => “column”, :sort => “column_name” – where column_name varies based on the link/column.

For the calculated solumns, I did the same thing, but set

:type => “calculated”, :sort => “method_name” – where method_name varies based on the link/model method.

I then changed my show method in the customers controller – instead of using the simple:

@customers = Customer.order(params[:sort])

like Ryan does in his RailsCast, I created a private method to return the ordered list of customers based on the type of sort I wanted.  In this case, the show method has:

@customers = sorted_customers(params)

Now, when creating the method to return the list of properly sorted customers, I started with the simple step of making sure the basic column sort would work with the logic.

def sorted_customers(params)
if params[:type] == “calculated”
# do something different
else
return Customers.order(params[:sort])
end
end

For the columns which matched database field names, this worked.  So I moved on to the next step, which was to use sort_by on the calculated fields, per Ryan’s answer in the Rails forum.  However, the following did not work:

def sorted_customers(params)
if params[:type] == “calculated”
return Customers.find(:all).sort_by { |customer| customer.”#{params[:sort]}” }
else
return Customers.order(params[:sort])
end
end

I tinkered with syntax around the customer._______ and how to allow for a variable method name based on a parameter.  After some searching, which was tough to figure out based on the keywords to use, I came across the following on StackOverflow (once again, to the rescue.)  You can call the “send” method on any object and pass in the name of the method you wish to use.  So, my end result is:

def sorted_customers(params)
if params[:type] == “calculated”
return Customers.find(:all).sort_by { |customer| customer.send(params[:sort].to_sym) }
else
return Customers.order(params[:sort])
end
end

Again, I make no representation about efficiency, but overall, this isn’t too complex a solution for a small app like mine.  When it grows up, perhaps I’ll have to find a better way of doing it.  Anyone out there have a more elegant solution?  Would love to hear/learn it:)



Connecting PHP to MYSQL on Mac OSX 10.6

So I have PHP set up and configured properly.  And because I’ve been doing some Ruby on Rails programming, I know that MYSQL works quite well.  But the key question is, does MYSQL work with PHP?

Interestingly, if you search the web for tutorials on using PHP with MYSQL on a Mac, you get tons of installation tutorials.  However, the ones that I found left off before actually testing to see if your database connection works from within a simple PHP file.

After some digging, I found a simple PHP and MYSQL tutorial on About.com.  It provides some simple create table and insert commands to test with, as well as some very simple PHP code to test it.  Here’s the key code to quickly test to make sure your PHP code correctly talks to MYSQL:

<?php
mysql_connect(“your.hostaddress.com”, “username”, “password”) or die(mysql_error());
mysql_select_db(“Database_Name”) or die(mysql_error());
?>

Awesome – just what I was looking for.  However, no sooner had I entered that than I got the message “No such file or directory.”  Not particularly helpful for troubleshooting.

After more searching, I came across this page from a place called HoffmanLabs.  If you scroll down, there’s a section called MYSQL database connection test.  There they have some very useful code that will actually tell you the type of error you’re getting.  In my case, the error was:

mysql_connect : No such file or directory
Error code :2002Error connecting to mysql

Ok, so I’m getting closer.  I paste that last line into Google, and find a ton of results.  One explains how I need to go into my php.ini file and change my mysql.default_socket setting.  Unfortunately, the setting already had the path that was recommended.  Huh.

Finally, after several more searches, I can across the correct answer.  Once again, StackOverflow (courtesy of Brian Lowe) to the rescue.

Basically, the mysql.sock file was in the /tmp/ folder when PHP expected it to be in the /var/mysql/ folder.  Now, I could move the file, but might that mess up my Ruby on Rails projects?  In looking at one of my database.yml projects, sure enough, Rails expects mysql.sock in /tmp/.

Fortunately, Brian’s answer to this question provided the perfect solution – create a symbolic link to the file.  Here’s his answer:

If you have /tmp/mysql.sock but no /var/mysql/mysql.sock then…

cd /var mkdir mysql cd mysql ln -s /tmp/mysql.sock mysql.sock 

If you have /var/mysql/mysql.sock but no /tmp/mysql.sock then

cd /tmp ln -s /var/mysql/mysql.sock mysql.sock

Works like a charm. Much thanks to Brian (check out his website).

Btw, if you’re a newbie and are told you don’t have permission to issue the mkdir command, remember to use “sudo” in front of it and enter your admin password to enable you to make that new directory.



Turning on PHP on my Mac

In addition to playing around with Ruby on Rails, I’m looking to re-familiarize myself with PHP.  The first step was to get my MacBook Air, with OSX 10.6, set up.

A quick search showed that PHP and Apache come bundled as part of OSX, so that sounds good.  But finding resources that provided consistent advice on how to get set up wasn’t.  Here are some of the sites I found useful:

FoundationPHP – the most specific and straightforward.  What makes it so straightforward?  Because it actually points out where hidden directories are and how to get to them.  While not a big deal for real developers, it’s still helpful for folks hacking around like myself.

StackOverflow – always a great resource for dev questions

Ok, next step is to get it to work with my installation of MYSQL (which I’ve been using successfully with Rails.)



Programming for kids

Been doing a fair amount of research and experimenting lately on ways to teach programming to kids.  I got my start following a great post on the subject by Marshall Brain (helps to show up #1 in Google for the search phrase:)

In my case, I’ve been looking for something that works for kids in the 6-10 year old range.  And of course, no search here would be worthwhile unless your kids have some inherent interest/curiosity in the domain.  But, assuming there’s interest, here are some other criteria I’ve found to be useful in evaluating options:

  1. It has to be engaging/entertaining: this rules out a lot of the text-based solutions, which is how I learned, though at a much older age.
  2. It has to enable very quick achievement/progress – if kids get frustrated, kiss this goodbye
  3. It has to match the kid’s expectations about what they’re trying to accomplish.  Odds are, kids aren’t interested in “learning to program.”  They’re more interested in creating their own version of something they are passionate about, and programming is how to do it.  Ever seen a kid create their own storybook or comic book?  Same thing applies here.

Ok, so what do I recommend?

First, I’d start out with Lightbot, a flash game that teaches instruction sets, functions, and even recursion.

It’s a lot of fun to solve the levels, and is a great starting point for starting to understand how computers make things go.  The levels start out very simple, but can quickly become challenging.  There’s a second generation version now, which allows users to create their own levels, a very cool concept that reminds me of the Lode Runner game from the 80′s.

Hopefully, Lightbot will provide a good balance of fun and teaching, and leave your child wanting to create something of their own.  If they get to that point, I’d then recommend Scratch, a downloadable programming framework from MIT.  I have to be honest, when we first tried Scratch, we thought is was pretty cool, but little more than an animation tool.  My kid wanted to create his own video game, and I didn’t see how to easily do it in Scratch, so started looking into more full-blown frameworks.  But I came back to Scratch after seeing a demo of a Super Mario recreation that was quite slick.

Scratch is great for game – its uses “Sprites” and backgrounds, with logic that can range from very simple to rather complex.  Plus, it teaches object oriented thinking and programming, which I like.  Rather than doing the traditional procedural learning first, then learning OOP, this sets kids up in the more modern framework right off the bat. You just build instruction sets by dragging and dropping “blocks” – a nice metaphor, given programming lingo around “blocks of code.”

The other phenomenal aspect to Scratch is the community that’s built up around it.  They claim more than 2 million shared projects from around the world, and there are tons of video tutorials, not only on the Scratch site but also on YouTube.

After watching one of the videos, my son and I built a version of Pong in about 5 minutes.  Happy programming.



Using annotations within Google Analytics

Wow, I feel so behind-the-times. Just started playing around with annotations in Google Analytics.  Very cool tool, and actually something I had considered as a potential app someone might write on top of GA (more on that below.)

Ever find yourself looking at your metrics, wondering why the numbers changed all of a sudden, digging in to find the source, then saying something to the effect of “damn, we need to write this stuff down when we release it?”  Well, that’s basically the point of annotations (at least from my perspective.)

Below is an example of a traffic chart (for a tiny website, but you’ll get the idea)

Basically, just pull down the small arrow tab below your GA chart to reveal more options, including the ability to “Create new annotation.”  Then just enter the date and a description.  What a terrific way to document changes you’ve made to your web site, so as you go back in history, looking at the numbers, you can see what you did.

Of course, this is a very manual process, and not very scalable.  Queue the idea of building an app layer on top of Google Analytics through their API.  Poking around a bit, you find lots of interest in being able to write annotations to your GA account through their API.  Unfortunately, while the need is well documented, it still hasn’t been implemented by Google.  Here’s hoping they add it soon.

Imagine, building into your deploy process the ability to publish release notes automatically (pull from Github, anyone) and append them to your GA account when the deploy happens.  Talk about transparency of cause and effect.



Tools to start a project with a distributed team

Looking to start a new project and want a simple, inexpensive way to manage communication and docs?  Basecamp not quite the right fit for you?  Well, I found a great combo in what in hindsight was a fairly obvious place.

For documents, Google Docs works quite well (though everyone involved needs a gmail address to access.)  But I find that insufficient for managing projects, as context is quickly lost in what turns out to be a too-long to manage list of docs.

I’m always been a fan of wikis for providing context and organization for docs.  I’ve used http://pbworks.com/ for a while, but have never loved it.  They also make it far to hard to actually pay them – can I just get an online upgrade option with the ability to enter a CC #?:)

Enter Google Sites – simple web page creation using wysiwyg editing that behaves much like a wiki.  Easy to create links to the docs you’ve uploaded.  Good access controls to – if you share both your Google Docs collections with the same folks you share the Site with, everything just works.

Further evidence of how cost effective/easy it is to get a project up and running.

- Kevin



Fun (not) with Ruby on Rails projects, bundle, and open source conflicts

Not sure anyone will ever read this, but I had some serious frustration starting up a new rails project (messing around, nothing serious) over the last couple of evenings. I had my mac configured and working well as recently as a couple of weeks ago, when I started and quickly abandoned a project. But I was able to get up and running with mysql following the steps in Rails Guide successfully.

Two nights ago? Different story. Get to the point of running rake db:create and get the following error:

WARNING: This version of mysql2 (0.3.7) doesn’t ship with the ActiveRecord adapter bundled anymore as it’s now part of Rails 3.1
WARNING: Please use the 0.2.x releases if you plan on using it in Rails <= 3.0.x
WARNING: Global access to Rake DSL methods is deprecated. Please include
… Rake::DSL into classes and modules which use the Rake DSL methods.
WARNING: DSL method MyProject::Application#task called at /Library/Ruby/Gems/1.8/gems/railties-3.0.5/lib/rails/application.rb:214:in `initialize_tasks’
rake aborted!
Please install the mysql2 adapter: `gem install activerecord-mysql2-adapter` (no such file to load — active_record/connection_adapters/mysql2_adapter)

Tasks: TOP => db:create
(See full trace by running task with –trace)

After lots of digging around StackOverflow, found two posts that were helpful:

http://stackoverflow.com/questions/5894102/bundle-command-the-wrong-mysql2-gem-always-0-3-2

and

http://stackoverflow.com/questions/6199301/global-access-to-rake-dsl-methods-is-deprecated

Basically, had to downgrade mysql2 and rake (meaning, uninstall the new versions and add lines to my gemfile to reference the older ones) because the latest versions automatically included with bundle don’t play well together.

I’m a super noob, biz guy, who probably has no business playing in open source frameworks, but I don’t care. If me posting this helps out one other noob, it was worth the effort. And thanks to both StackOverflow and the folks who answer questions there for helping me get productive (a loose term) again.



And we’re up an running…

Not much to share yet, but you can check out our blogroll on the right to get an idea of the types of products and services we’ve launched.