Rails Sessions

Posted by John
on Sunday, 09 March 2008

rails is love

To make a truly intelligent web application your gonna sooner or later have to play around with Sessions, which is basically a Cookie's big brother.

Store in DB

Now Rails initally will store all it's session data in a text file within the /tmp/sessions directory of your rails app, which is usually ok, but if you're gonna build a production-ready app you're gonna want to up the ante somewhat and store them in your DB.

This is simply done by opening up your environment.rb file and un-commenting the following line...

(within /config/environment.rb) config.actioncontroller.sessionstore = :activerecordstore

Then in the command-line generate a RAKE DB migration for your Session objects (so they're stored in your db from now on).

rake db:sessions:create rake db:migrate

Bingo, you now have a table within your database hooked up and ready to store your session data perfectly.

Storing Session Objects

Now that you've got your DB storing your session data, why don't we start creating some session objects.

This is done by...

session[:order] = 'ASC'

Here, we've simply created a new session object, storing in it a text value of 'ASC'; cool eh?

We can then check to see if our session is empty via...

if session[:order].blank? ..do stuff..

So if our session object contains nothing we can initialise it correctly.

Common Gotcha

Now one of the good things with switching sessions over to your db is that it'll secure your app a little bit better and your performance will improve.

Plus if your building your app on your dev machine, then transfer it to your live box, but can't find a reason why your sessions don't work there it's usually down to file permissions for the session file; by switching sessions over to a db you remove any future problem of this.

Good eh,

Change .rhtml => .erb

Posted by John
on Tuesday, 18 December 2007

In a bout of syntactical changes, Rails 2.0 harks the end of the .rhtml file extension; to be replaced with .erb

To change all your existing .rhtml files to .html.erb, run:

for f in $(find . -name '*.rhtml') ; do c=$(dirname $f)/$(basename $f .rhtml).html.erb ; hg mv $f $c ; done

The .html is to help with working out what contents are in the file, as it could in theory have both.

  • .html.erb = html
  • .css.erb = css

p.s. the script above doesn't do .css.erb, that's something you'll have to decide whether to use.

Thanks to Duncan Ponting for this.

Rails 2.0.2 from elsewhere

Posted by John
on Monday, 17 December 2007

Rails 2.0.2 has just been released, more bugfixes than new addons, but worth the download (running it here now).

However it's only available from http://gems.rubyonrails.org at the moment, but to get it do:

sudo gem install rails --source http://gems.rubyonrails.org

Here, your actually specifying which repository to use to find the gem.

To see what your default source location is:

sudo gem sources

Enjoy,