Category Archives: Rails

Use ActiveRecord scopes, not class methods, in Rails to avoid errors

In Rails, scopes provide a shortcut your models’ most frequently used queries.

For instance, on a Widgets model, you might have a scope called available, which runs Widgets.where(“quantity_in_stock > 0”).

You can achieve the same effect with a class method on the Widgets model.

In either case,  Widget.available returns an ActiveRecord relation with the matching records, just as if you had called the where method directly.

If class methods and scopes do the same thing, why would you use one over the other?

Scopes, it turns out, are less error-prone.

To find out why, we need to examine a more complex query.

Say that widgets have a discontinuation_date. Once a widget hits that date, it is no longer available.

We’ll expand our available scope/method to take the discontinuation_date into account.

Here, we show widgets that are currently available and haven’t hit their discontinuation date.

Now, say you called Widget.available(nil).order(“title”).

The class method returns a nil object, and you receive an error stating that there is no method order on a nil object. Not good!

The scope, on the other hand, returns a blank ActiveRecord relation. Running order on a blank ActiveRecord relation returns that same relation. No error. Good!

Choose scopes over class methods in your models.


Scopes avoid the problem of nil objects, which make code messy and error-prone.

Scopes don’t return the dreaded nil objects, instead returning a blank relation on which you can run any ActiveRecord method. You could say they implement the null object pattern.

The most direct and bullet-proof way to avoid nil object errors is to avoid nil objects
If You Gaze Into Nil, Nil Gazes Also Into You by thoughtbot

For more details on the differences between class methods and scopes, check out Active Record Scopes vs. Class Methods on Plataformatic’s blog.

Easy data grids for your Rails app, with Wice Grid

Sometimes we need to show tables of data in a Rails app, sort of like souped-up spreadsheets. The tables, or grids, should handle tons of records, support searching and filtering, and allow for customization.

Ever try coding a data grid yourself? It’s hard. You need to implement pagination, filtering, searching, ordering, etc., every time. Why not use a pre-built solution and built off of it instead?

Wice Grid is the quickest grid solution out there for Rails. It takes care of both the client and server. It’s not AJAX-y and gorgeous, but it’s functional and reliable.

At Cook Smarts, we used Wice Grid to improve the admin interface without leaping to a full-scale solution like Rails Admin.

For instance, Cook Smarts’ customers can purchase gift certificates for their friends. Site admins need to see all gift certificates and search for particular ones. The easiest way for them to do this is through a data grid.

To get started, check out the Wice Grid page on GitHub.

Getting up and running is easy:

Follow the installation instructions on the Wice GitHub page

Add the grid code to a controller method, with the model whose data should appear in the grid.

Then, add the grid code to a view, referencing the grid you specified in the controller. Add columns, specifying the attribute as the field name in the database and the name as the text to appear in the header of the grid.

Customizing the order, filtering, search, and pagination is easy. Check out the Wice Grid GitHub page for instructions.

Wice Grid would be even better if it incorporated AJAX, to avoid page reloads when searching, for instance. However, that is the trade-off for its extremely quick setup.

Rails Admin, a quick admin interface for your Rails app

Most apps have an admin interface, a place where the developers and special users can make changes to the database.

Creating your own admin interface is time-consuming, and can take the focus away from developing user-facing features. Figuring that admin interfaces have similar needs, frameworks have emerged that help get your started.

With Rails Admin, you can edit your database on dev and production, in a user-friendly way, without coding your own admin interface.

Its closest competition is Active Admin, which I see as too complex for a convenience tool.

Quick start

Add this to your Gemfile:

In a terminal window, while inside the path of your app, run

You now have an admin panel, located at http://yourapp.com/admin

Two essential steps remain.

One, make sure your models are defined correctly. Have you defined associations, like belongs_to, has_one, and has_many, as needed?

Two, restrict access to your admin interface. tell Rails Admin who should be allowed access.

How it looks

My app will deliver online courses. So far, it contains two tables:

  • Lessons
  • Components

Each component falls under a lesson. In Rails-speak, a component :has_one lesson, and one lesson :has_many components.

Rails Admin looks at my models and shows them in its left navigation. I never had to separately tell Rails Admin the structure of my database.

Rails Admin - left navigation

When I click on a table, I see its records.

Rails Admin - record editor

I can edit records. Since components are related to lessons, I can add components to lessons and associate each component to a lesson, all within Rails Admin.

Enjoy!

Rails Admin can help you launch faster by removing the need to develop your own custom admin interface.

At the start, either use a quick solution like Rails Admin or create your own custom admin interface. You can always move from Rails Admin to a custom interface later.

For more information about why you’d use Rails Admin, check out this presentation. Jump into the details by visiting the Rails Admin wiki.

Editor’s note

This is the beginning of a new series, Up and Running. We’ll tell you how to get up and running with several developer tools, quickly and easily. Get updates about what we cover next.

Markdown in Rails with Redcarpet

Why it’s awesome

Redcarpet is an extremely quick way to show Markdown as formatted HTML in your Ruby / Rails app.

Markdown is a simple way to format text. Think of it as an easier version of HTML.

In Markdown, this:

Becomes this:

Hello, this is bold and this is italic.

Users can enter Markdown into regular text fields, and you can store it as text in your database. Then, with Redcarpet, you can render the Markdown as HTML.

You might allow users to comment within your app using regular text or Markdown, and then show those comments with formatting.

Quick start

Add this to your Gemfile:

Store Markdown in a regular text field within your database. To the user, you can present a plain text field and link to a Markdown quick reference.

Once some Markdown is in your database, you can convert it to HTML in your controller…

… then show the resulting HTML in a view:

In the example above, we used the body of a comment as an example.

Check out the documentation and this video overview.

In closing

I love Markdown, and will use this tool whenever I need to maintain static, formatted content in my app.

Rolling out Markdown editing to end users is trickier, since many may not be familiar with it. However, allowing people to use Markdown is different from requiring it. If you allow Markdown in comments, for instance, place a note under your new comment field stating that Markdown is an option, and link to a quick reference.

The Up and Running series

This is part of the Up and Running series, showing you how to jump onboard to useful developer tools. Hear about what’s coming next by joining our e-mail list.

User analytics for your Rails app, with Ahoy

Google Analytics provides solid, aggregate statistics for your Rails app. It answers questions like, “How many visitors do I receive a day?” and “Which parts of my app are most popular?”

It cannot track individual users over time, however. Questions like, “How long does the average user remain active over time?” or “How long does it take the average user to go from a free to a paid account” require user analytics.

Services like Mixpanel and KISSMetrics specialize in user analytics, offering robust tracking and reporting for a fee.

There is another option, a free, open-source Ruby gem (technically, a Rails engine) called Ahoy. In just a few minutes, you can have robust user analytics for your Rails app.

Let’s walk through an example; say that on our site we want to track visits and actions for each user.

First, install Ahoy and perform the post-installation steps. This takes only a few minutes.

Track visits

Visit tracking starts immediately after you install Ahoy. You can customize the length of each visit (i.e. after how long does one visit turn into two); it defaults to 4 hours.

Ahoy automatically ties each visit to a user. You not only know how many visits you receive each day, but which users visit the most. Already, we have user analytics.

Track events

Users do stuff in your app. If you have a todo list app, for instance, they add todo items. In modern-day apps, user actions may be processed on the server with Rails and/or on the client via JavaScript.

Ahoy lets you log user events in your Rails code or your JavaScript code.

For instance, if a user adds a to-do item on the front-end, log it with JavaScript:

If the user takes an action handled by your Rails code, log it with Ruby:

Reporting

Ahoy does not provide a dashboard for reporting, though it’s in the pipeline and they offer advice for building your own.

Third-party services vs. Ahoy

Mixpanel and KISSMetrics offer advanced reporting out of the box, but have a cost and require you to send your user data to a third party. If you choose to leave either service, extracting your data in a useful way is difficult.

Ahoy is free and your data stays local, but you’ll spend time creating a stats dashboard and reports.

There is no right answer, but while evaluating user analytics tools, be sure to consider Ahoy alongside the paid options.

Rails and external services: allow for failure

At Cook Smarts we rely on external services for payments, image processing, and more. Sometimes, the app will fail to reach a service. Perhaps the service is down or there’s a network error somewhere along the line.

How can we tolerate such errors with a minimum impact to the user?

Here’s an example of how we addressed a recurring error with an external service:

A user can export a recipe as a PDF, including an image of the meal.* We retrieve the appropriately-sized image form reSRC, our external image processor.

PDF exported recipe from Cook Smarts

Occasionally, the connection to retrieve the image times out, preventing the image from importing into the PDF. Before, this caused an exception, preventing the user from exporting the recipe at all.

For a better user experience, we now show a friendly error message in place of the image.

Exported PDF recipe from Cook Smarts with image error message

To show the friendly error instead of a fatal exception, we use ‘begin’ and ‘rescue’ in Ruby, in the midst of our Prawn PDF code.

Fault tolerance is crucial when using external services. Assume that your app and the services will clash sometimes, and plan accordingly.

* Eventually, we’ll cache these PDF’s, but for now they are generated whenever a user requests them.