«

»

Jul 29

Rails To Grails Tips – Closures and Models

One frustrating thing I’ve discovered with Grails is the way data is sent to the view pages.

In Rails, it looks a little like this:

@scenario = Secenario.new
@scenario.title = "New Scenario"
@scenario.description = "Add A Description Here"

render :view => 'create'

This snippet creates a new Scenario object, populates it, and tells Rails to render the create.rhtml file, with the @scenario object in the page’s model, helpfully known as @scenario

In Grails, it looks like this:

def scenario = new Scenario()
scenario.title = "New Scenario"
scenario.description = "Add A Description Here"

render( view: create, model: [ scenario: scenario ]) 

and, similarly, Grails knows to render the create.gsp file, and the scenario object is available to the page as scenario

Which isn’t terribly different, and fairly easy to use.

The problem comes in because of the way Grails uses closures to provide the action methods on the controllers (edit, create, delete, save, etc).

In Grails, you might have a action method as such:

def create = {  // closure of action method here }

Now, look at the previous Grails code. Do you see the issue? Yes – create is now overloaded, and in some cases, Grails will attempt to find a page named Controller_closure_blah_blah_blah.jsp, which is obviously completely wrong.

The fix is simple:

render( view: 'create', model: [ scenario: scenario ]) 

Basically, make sure you always use quotes for your string values, even though the Groovy language allows you to leave the quotes off. Otherwise, you’ll occasionally get frustrating and confusing results.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>