Monday, December 27, 2010

Some Names Are Protected

This post falls into the category of "I knew that, but I didn't think about it."

I'm working on a project that is a small, fairly simple Rails application. Or seemed to be until I ran into this piece of code:
<%= Chart::TYPE_OPTIONS.each do |o| %>
<%= f.radio_button(:type, o) %>
<%= f.label :type, t("activerecord.attributes.chart.values.#{o}"), :value => o %>
<% end %>

This is on the new chart form, and it's one of several fields (but the rest aren't important). Everything was working fine except this one field; the field just wouldn't save. It kept throwing "Can't mass-assign protected attributes" warnings.

Anyone see the problem? This one took me a good 10 minutes.

Yup, "type" is a protected keyword. Don't name attributes "type".

I renamed it to "chart_type" and lo and behold everything works. I could probably have made type work, but in general I'd rather rename the attribute than try to figure out all the places I have to do something odd. The moral of today's story is: know your language and your framework well enough to know what words you just shouldn't use.

No comments:

Post a Comment