Garbage Burrito

Don't forget about 'assigns' in Rails

Don't forget about 'assigns' in Rails
Ben Kittrell - 11 07, 2006 @ 12:40AM
Comments: 0

I had a need to set a property in a before_filter proc in the controller, that was available in the layout.  Back when I first did this I first tried just setting an instance variable, but that didn't work.  So then I just set a request parameter, which seemed to work just fine.  I wasn't particularly happy with this, but I lived with it until it started popping up in my urls.  This just started to make me nervous, and certainly made me cringe.

So I started perusing the Rails API, and found that the controllers have an 'assigns' property.  This is a hash like request, however it's what creates the instance variables in the view.  This is available in the before_filter procs, so viola.

Controller:

    before_filter(:only => [ :index ])
    { |c| c.assigns[:css_mode] = 'albums' }

View:

    <body class="<%= @css_mode %>">

This is one of those things that's not incredibly obvious, but can be very useful.

Comments: 0

Post a Comment




powered by : Doodlekit Online Free Website Builder : developed by : Doodlebit™ Website Company