Moving from Rails to Grails (Differences and Similarities)

Posted by David Estes on Jan 15, 2014

Rails and Grails are both great, powerful frameworks with many core similarities and differing approaches. They both share a strong preference to convention over configuration and they both follow the MVC style of frameworks (though Grails adds a new concept called services we will go into later. I have had the pleasure of working heavily with both frameworks and learning about their various quirks. This is coming from the perspective of a formerly full time rails developer and the transition to Grails.


These frameworks have several thing in common, and rightly so as Grails came after being inspired by Rails. They both share an MVC stack, they both have an ORM, and they both have similar template languages. Now, there are some things that have not progressed as far as Rails 3.2 in the Grails area (currently version 2.3.4). As a matter of fact, elements of Grails feel like the Rails 2.3 days. Back then Rails had dynamic finders in active record just like Grails does now ( although some would argue GORM is more advanced than active record is today). But, there are several facets of Grails that have gotten more attention than Rails did, or used different concepts.

ActiveRecord & GORM

This is probably the biggest area of confusion and frustration when moving between the two frameworks. But it is also probably the best place to start. GORM is the Grails Object Relational Model interface. It is primarily backed by Hibernate ( A powerful Java ORM), although more recently GORM has been decoupled from Hibernate to allow for connectivity to alternative database mappers and NoSQL datastores. Another important difference between these ORMs is how they define their properties. ActiveRecord tends to rely on migrations and observes the final table structure to build its accessors, while GORM prefers you strongly type your fields in whats called a Domain class.

Rails Example:

class SpudSnippet < ActiveRecord::Base
  validates :name, :presence => true
  validates_uniqueness_of :name, :scope => :site_id

Grails Example:

package spud.cms

class SpudSnippet {
  String name
  String content
  String format = 'html'
  Date dateCreated
  Date lastUpdated

  static mapping = {
  static constraints = {
    name blank:false
    content nullable:true

Typically, upon startup Grails can analyze the db schema and add missing fields to the database. More advanced table adjustments can be performed via a database-migrations plugin which gives Grails a similar means of migrating Schemas that Rails has.

The Hibernate Session

This is probably one of the biggest areas of confusion when coming from ActiveRecord. A Session in Grails GORM ( database session, not HTTP session ) can be both transactional and non transactional depending on where the code is being executed. Grails has created a very strong Transactional layer when interacting with data that can come in quite handy for high priority data integrity applications or Enterprise type databases. Rails does have an ability to create a transactional state and perform rollbacks, and commits as well, however this layer is not common and typically off by default.

Another side affect of using Hibernate with GORM is the concept of dirty checking. In rails lets say I fetch a record and adjust the name field. In order for this change to persist I must call save. That makes sense and even in GORM save calls can and should be made. However, at the end of a request cycle, when a GORM session is flushed, a dirty check operation is performed. Objects that are binded to the session are compared against their original values and if changes are detected, they are persisted. Seems like a small difference, but this can have larger implications on how your perform your database operations. During the lifecycle of a database session, the session can be flushed many times. One common occurance if an unexpected session flush is executing a find query on a Model type after editing a property from a previously fetched record. Hibernate will first flush the session before attempting to run the query because it has no idea wether or not the previous change could affect the query results. So, as you can see, there are some easy ways to get yourself in trouble with unnecessary overhead on your database. there are a few tricks to detach records from your session so they do not get dirty checked.

def snippet = //Fetch snippet by id 
def snippet = SpudSnippet.withCriteria(readOnly:true, uniqueResult:true) {

The discard / readonly directives results in a detached record. these records arent necessarily read only though and changes can still be persisted to the database via a save call. another important trick to be aware of is the 'withNewSession' method. this allows you to execute queries on a new session so as not to affect the current one. (Very useful in beforeInsert and beforeUpdate hooks).

Query Builder

GORM has a very powerful query builder syntax, and recently added a chainable where method similar to ActiveRecord , but far more powerful.

Rails Example:

snippets = SpudSnippet.where(siteId:0).where(name: "Footer")

Grails Example:

def snippets = SpudSnippet.where{siteId == 0}.where{
 name == "Footer" }.list()

Notice that the groovy version uses standard boolean logic operators. This magic allows for some pretty powerful query structures and is chainable. For More information check out the docs on Where Queries.

GORM also provides some advanced criteria builders as well as the ability to use HQL ( Hibernate Query Language ).

def snippet = SpudSnippet.createCriteria().list {


def snippet = SpudSnippet.executeQuery("from SpudSnippet where siteId = :siteId and name like :name",[name: 'Footer%', siteId: 0])


There are a few other caveats worth mentioning. One of which is using hasMany associations in GORM. These can be very expensive in grails due to dirty checking and other various forms of validation. It is more common to define the associaton on the associated model instead (kinda reverse).


A new concept added to the Grails framework that does not exist in the Rails framework is Services. Services are singleton classes where methods can be stored for performing your business logic. Rails prefers using fat models and Concerns where these helpful logical methods are injected directly onto the model object. Grails decided to move that out into a new layer which actually skinnies up your models and adds some other niceties that you normally wouldn't have. One of these niceties is that services are injectable and default transactional (Meaning if something fails during the process, your database state safely rolls back). A service can be injected / used by almost any class due to the power of Spring Beans. All one has to do is make a service class (must end with Service) in the grails-app/services folder

class SpudMenuService {
  def someMethod() {
    //Perform some database logic here

A service can be injected into a controller by simply defining a variable with a lowercase camel name and it automatically gets injected:

class MenuItemsController {
  def spudMenuService

  def index() {
    return [menus: spudMenuService.someMethod()]

Another note on services is that you can turn off their transactional behavior to reduce overhead when it is unnecessary. To do this you simply add static transactional = false to the top of the service class definition.


Grails and Rails controllers are pretty close to the same, save for a few things. Both support passing the instance variables of the controller class to your views (although this is not as useful in Grails since you have to define those variables at the top of the controller). Up until recently, Grails did not support having multiple controllers with the same name, even if they were in a different classpath. This has recently changed with the ability to scope requests to a plugin name or by using a controller namespace. A namespace can give you similar functionality to the use of namespaced controllers in rails. Another difference is the resource/REST action mappings between grails and rails controllers. In rails you would have the following:

class Spud::Admin::SnippetsController
  def index

  def new

  def create

  def edit

  def update

  def destroy

Where as in Grails you would have something like this:

class SnippetsController {
  static namespace = "spud_admin"

  def index() {

  def create() {

  def save() {

  def edit() {

  def update() {

  def delete() {

As you can see it is slightly different, although not too bad.

Filters / Interceptors

Another difference between the 2 frameworks is their use of interceptors and filters. In Rails it is easy to add a before_filter declaration to the top of your controller, and this interceptor can become inherited. In grails this is a bit more involved and actually supports a few other options. One option is to define a beforeInterceptor. These can be scoped to specific actions in your controller. If, however, you would like to define a broader filter that applies to many controllers, Grails has the concept of a Filter class that can get added to your grails-app/conf directory. The Filter is a class that can define a controller match pattern to determine if it should intercept the web request or not.

There is also a broader jvm style filter called a ServletFilter. Servlet filters run at a higher level than everything else previously mentioned. It is actually where the UrlMappingFilter that resolves urls to controllers exists. You can create your own ServletFilters and use the Webxml plugin to control ordering and registry.


Well, we've made it this far (are you still with me?). Grails and Rails have some similar view concepts, and even similar inline groovy/ruby syntax. However, Grails recommends against using this form of syntax in favor of Taglibs. A Taglib is a namespaced method that looks a lot like an html element: For example creating a link my look like this:

<g:link controller="home" action="index" class="btn">Home</g:link>

Not too bad right? You can even define your own taglibs in your project. For information on that check out the documentation

Grails even has a similar means to create the rails style content_for blocks. Under the covers, Grails is using something called Sitemesh (in case you need to google tricks for Sitemesh). Sitemesh provides most of the framework for applying layouts from grails-app/views/layouts to your views. You can define the layout you want to use via the controller, via a meta tag on the view, or even via a <g:applyLayout name="main"></g:applyLayout> block. You can even utilize this functionality to create sub layouts and inherited layouts, though this is not well documented at the time of this writing.

Content blocks are also a bit underused in the Grails ecosystem but I find them very powerful for organizing my layouts. The equivalent for a content_for block is the use of the content tag and the yield property is replaced by the pageProperty tag. i.e.:


<g:applyLayout name="application">
<content name="sidebar>
  <p>Standard body text goes here</p>


  <div class="sidebar">
    <g:pageProperty name="page.sidebar"/>

Not too bad right? Note: The name of the content tag has to be prefixed by page. when spitting it out with the pageProperty tag. There are a ton of built in tags for gsp, including form helper tags and more. Check out the docs for specifics.

Static Assets

This is where I get to make a small plug for asset-pipeline. Grails supports several means for serving your static assets (images, javascript, stylesheets, and more).


By default, a Grails project comes configured to use the resources plugin. This was added as the default means for serving up static resources in grails 2.2.x. It is capable of handling asset bundling, caching, zipping, and minification. (Note most static assets in grails are served out of the web-app folder and unlike rails plugins, grails plugins come bundled with their assets as well).

There are, however, a couple downsides to the use of the resources plugin. This includes slow app startup times (as the assets are reprocessed every time it is relaunched), disconnected bundling (you must define groups of assets in modules using a Resources.groovy file), and cumbersome use of compiled asset formats such as Coffeescript, and LESS.

Asset Pipeline

The asset-pipeline plugin is an alternative plugin that can be used for serving assets. It works and behaves in a very similar way to the Rails asset-pipeline (but it doesnt typically bite you in the ass like the Rails one does).

With the asset-pipeline you get to store your assets in grails-app/assets and they get precompiled automatically upon WAR creation. A few differences from the rails equivalent, is that you dont have to use special asset path helpers in your stylesheets to point to images. The Grails asset-pipeline automatically scans your css for all urls and correctly makes relative path adjustments and cache digests. (Yes, you can actually drop in the Bootstrap css from source and have your glyphicons available immediately). The asset-pipeline is also, by default more inclusive of its precompiled files. By default, it will try to precompile every file it can find in your assets folder unless specifically black listed via config. This makes it a bit less of a surprise for developers who have everything working in development mode when moving to production. Even with all this, the grails asset-pipeline is much faster at compiling assets than its rails equivalent and only compiles changed files.

There are also several extension plugin addons available for the Grails asset-pipeline. These include, plugins for LESS, Coffeescript, Handlebars, and even Emberjs.