I do disagree with him on one point though; where he favours explicitly hiding attributes with attr_protected I'd much rather people started with everything hidden and chose to explicitly expose attributes with attr_accessible.

This has long been a bugbear of mine with Rails. So much so that the first plugin I wrote was explicit_assignment.rb, below


class ActiveRecord::Base
    attr_accessible
end

That might not look like much but it's three powerful lines of code.

Calling attr_accessible with no parameters in Base effectively means all application models start life completely ignoring calls to model.attributes = attrs. If I want to use mass-assignment for any value I have to specifically ask for it.


class AppModel < ActiveRecord::Base
    attr_accessible :a_small_series, :of_accessible, :attribute_values
end

The only issue I've had is that this does tend to screw up a number plugin models that rely on mass-assignment. In this case all you have to do is read through all the plugins you use, make judgment calls on what should be accessible and update accordingly. What? You mean you don't read every line of evey plugin you use? Nah, me neither, so I usually just change the explicit_assigment plugin to:


class AccessibleRecord < ActiveRecord::Base
    self.abstract_class = true
    attr_accessible
end

I then subclass all my application models from AccessibleRecord.

Yes, this is perhaps a bit verbose for a framework that prizes terseness and DRYness above all else but, if you value security too, I think it's worth the extra text.

1 Comment On This

Hey Gav! Surprise, surprise! Well done man, at last! I like all those wee details like the ampersand sign and menu tabs (had similar idea for my own thing grrrr!) and the logo (awesomness – best so far – have you designed it?) and bits of JS enhancements (flickr zoom etc.) What CMS is it running on?

PS You've pushed me to re-design my own blog now ;-)

Leave a Comment

You can use the Markdown for links, strong, and emphasis tags in your comment.

From March 19th, 2008.

This article is tagged with Ruby on Rails, security, and web development.

Commenting is currently enabled. There are 1 comment so far.

Related Articles.

Living on Version Control.

has_web_fallback

Rebinding Spaces in Leopard.

The Beautiful Game.

Mass attribute assignment in Rails.