Rails attr_accessible does not work for: type?

Im trying to set the inheritance model type of a single table in a form. Therefore, I have a selection menu for the: type attribute, and the values ​​are the names of the STI subclasses. The problem is that the error log keeps printing:

WARNING. Cannot assign these protected attributes: type

So, I added "attr_accessible: type" to the model:

class ContentItem < ActiveRecord::Base # needed so we can set/update :type in mass attr_accessible :position, :description, :type, :url, :youtube_id, :start_time, :end_time validates_presence_of :position belongs_to :chapter has_many :user_content_items end 

Does not change anything, ContentItem still has type: type = nil after calling .update_attributes () in the controller. Any idea how to bulk update: type from a form?

+4
source share
5 answers

Duplex on railsforum.com found a workaround:

use a virtual attribute in forms and in the model instead of dirtectly type:

 def type_helper self.type end def type_helper=(type) self.type = type end 

Worked like a charm.

+6
source

we can override attributes_protected_by_default

 class Example < ActiveRecord::Base def self.attributes_protected_by_default # default is ["id","type"] ["id"] end end e = Example.new(:type=>"my_type") 
+20
source

You should use the appropriate constructor based on the subclass you want to create, instead of calling the constructor of the superclass and manually assigning the type. Let ActiveRecord do it for you:

 # in controller def create # assuming your select has a name of 'content_item_type' params[:content_item_type].constantize.new(params[:content_item]) end 

This gives you the benefits of defining different behaviors in your initialize () method or subclass callbacks. If you do not need these benefits or you plan to change the class of an object often, you may need to rethink the use of inheritance and just stick with the attribute.

+9
source

"type" sometimes causes problems ... Instead, I usually use a "view".

See also: http://wiki.rubyonrails.org/rails/pages/ReservedWords

+4
source

I executed http://coderrr.wordpress.com/2008/04/22/building-the-right-class-with-sti-in-rails/ to solve the same problem as mine. I'm new to the Rails world, so I'm not sure if this approach is good or bad, but it works very well. I copied the code below.

 class GenericClass < ActiveRecord::Base class << self def new_with_cast(*a, &b) if (h = a.first).is_a? Hash and (type = h[:type] || h['type']) and (klass = type.constantize) != self raise "wtF hax!!" unless klass < self # klass should be a descendant of us return klass.new(*a, &b) end new_without_cast(*a, &b) end alias_method_chain :new, :cast end class X < GenericClass; end GenericClass.new(:type => 'X') # => #<X:0xb79e89d4 @attrs={:type=>"X"}> 
+1
source

All Articles