Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActiveRecord::DangerousAttributeError - attribute? is defined by ActiveRecord

I've got an existing db with some tables using the column name attribute. I simply cannot change this name as it would mean recompiling our whole application.

When trying to access the db, I end up with:

attribute? is defined by ActiveRecord

First up I tried using datamapper but I can't get on with it and am finding myself fixing things which shouldn't be broken - like nested attributes....

So, I've come back to ar and am using this to solve the issues:

class Radcheck < ActiveRecord::Base
  set_table_name 'radcheck'
  class << self
       def instance_method_already_implemented?(method_name)
         return true if method_name == 'attribute?'
         return true if method_name == 'attribute_before_type_cast'
         return true if method_name == 'attribute='
         return true if method_name == 'attribute'
         return true if method_name == 'attribute_changed?'
         return true if method_name == 'attribute_change'
         return true if method_name == 'attribute_will_change!'
         return true if method_name == 'attribute_was'
         return true if method_name == 'attribute_column'
         return true if method_name == 'reset_attribute!'
         super
       end
   end
end

But that's messy and is messing me around when I actually try and access the table...

What are my other choices - are there any good ways around this little bugger?

like image 662
Jenny Blunt Avatar asked Dec 28 '22 11:12

Jenny Blunt


2 Answers

I'm going to answer this myself because the above didn't fix totally.

Despite renaming the column in my controller:

 @radcheck = Radcheck.find(:all, :select => 'attribute AS attr')

I still couldn't actually use attribute.

In the end, I used this excellent gem, safe_attributes, to do the trick. Now I can call with this:

<% @radcheck.each do |radcheck| %>
<%= radcheck.attr %>
<% end %>
like image 149
Jenny Blunt Avatar answered Jan 13 '23 11:01

Jenny Blunt


Without worrying about ActiveRecord's reserved attributes, just add a gem in your gemfile and the gem will take care of name collisions automatically.

gem 'safe_attributes'

Enjoy RAILing..

like image 31
RAJ Avatar answered Jan 13 '23 10:01

RAJ