How To: Add A Custom Model to Your Spree App

Spree is a fully-featured e-commerce system available as a modular set of Rails 3 Engine gems. Although it comes with a ton of functionality out of the box, Spree can take a little getting used to due to slight differences in convention from a standard Rails deployment. What we'll discuss today assumes that you've already installed Spree and understand the directory structure. Onward…

Migration and Model

To start adding the custom model, we'll do what we're used to and create a migration. Run the migration command from the terminal and add a name and description field. Next, let's create our model class. In this case, we just want to check that all the fields are filled out. If you have custom logic, you'll want to write some tests, of course.

Admin Controller and Routes

After we've created our model, let's go ahead and setup our admin controller. Spree utilizes a gem called resourcecontroller that abstracts out all of the standard Rails RESTful resources controller methods in to a simple helper call: resourcecontroller. ( Also shown below are a couple of customization examples. ) In our routes, it turns out we won't want the show action, so we'll add an exception.

Admin Views

To begin setting up our views, we'll add a tab in to the Spree navigation bar. Spree provides hooks that we can utilize to modify things such as the admin navigation bar.

Now that we have our admin tab, we can add our admin index view.

And, for this file to work, we need to add our sub-navigation. ( I had trouble getting the active tab highlighting to work, so you can see an example hack for overriding the tab helper below. )

Let's finish up by creating the rest of our standard resource view files…


Spree makes good use of the I18N gem, so having your localization file setup is important.


As you can see, Spree makes good use of convention, but it might take a bit to get used to. After completing the above, you should have a custom model with an admin panel fully integrated in to the existing Spree admin. We also created sub-navigation that also utilizes Spree's active tab convention. At this point, you should be ready to integrate your custom model in to the front-end!

Tally ho!