Select Random Rows Using Ruby On Rails

Posted by jcnnghm Fri, 07 Aug 2009 00:59:00 GMT

Today I was looking for a way to randomly select rows from a database using Rails. I implemented the following message, which will randomly select a specified number of random rows, or as many rows as are available if the requested number is greater than the available number.

def find_random(random_count, options = {})
  if random_count > count(options)
    find_every(options.merge({:offset => rand(count(options) - random_count + 1), :limit => random_count})).sort_by{rand}

The code first attempts to determine if there are enough records to randomize. After that, it randomly selects an offset and returns the specified number of rows at that offset, after randomly sorting them. The benefit that this has over the other methods, is that it should scale well with very large data sets. The downside is, of course, that the are sequential from the given offset. In my situation, this works fine. Depending on what the data is used for, this may not work well for you. If that is the case, the approach I would take is to randomly generate a number of offsets, and select individual records at each offset. This should perform reasonably quickly as long as only a random items are selected.

Rails Forum Plugins 2

Posted by jcnnghm Thu, 06 Aug 2009 00:09:00 GMT

 I’ve been looking into adding some forum functionality into my Baltimore and Annapolis bars website.  While I was researching different forum implementations to find out what kind of forum I’d like to have on the site, I came across a couple of rails plugins that will take care of all the heavy lifting.

First is Savage Beast, the second version of a plugin designed specifically to add forums to Rails sites.  While Savage Beast is functional, it doesn’t appear to be actively updated.  It was forked a few months ago to bring it in compliance with Rails 2.3.  Unfortunately, as of this writing, that hasn’t been completed yet.  Savage beast is definitely worth watching, but at this time I think it would take too much work to get it production ready.

On the other hand, we have Community Engine,  Community Engine uses the Engines plugin, now integrated into rails, to add all kinds of social networking features into your rails project.  In addition to forums, the plugin brings user profiles, blogs, photos, and a messaging system.  The plugin has a ton of github activity, forks, and followers, and is definitely under active development.  Even better, the plugin is already Rails 2.3 compliant.  The only apparent problem with Community Engine is how many features it really has.  I have a feeling it could be quite difficult to integrate the software into an already-developed website.

I intend to begin integrating it over the next few days, and I’ll keep this up to date with how it’s going.