Engin Kurutepe
Engin Kurutepe

Reputation: 6747

rails: can't mass assign to these protected attributes while trying to set STI type during create

I have just started out learning rails and ruby, so please bear with me if this is too dumb.

There are several different AppModule types in my app, which have different behavior but similar data, so I save them using single table inheritance.

However when trying allow the user to explicitly select which type they want in app_modules/new.html.erb I get the warning WARNING: Can't mass-assign these protected attributes: type. Here is the relevant code:

<% form_for(@app_module) do |f| %>
  <%= f.error_messages %>

  <p>
    <%= f.label :type %><br />
    <%= f.select( :type, options_from_collection_for_select(AppModule.subclasses().map{ |c| c.name}, 'to_s', 'to_s')) %>
    </p>

  <%= f.submit 'Create' %>
 <% end %>

I have tried explicity setting attr_accessible :type in the model file but it didn't work

I am using rails 2.3.8 and ruby 1.8.7.

Any help greatly appreciated, thanks...

Upvotes: 0

Views: 1871

Answers (3)

Adam Lassek
Adam Lassek

Reputation: 35515

You shouldn't ever have to set the type attribute manually. Use the subclasses you created instead.

model = params[:app_module].delete(:type).constantize
model = AppModule unless model.is_a?(AppModule)
@app_module = model.new(params[:app_module])

Upvotes: 6

Dhanu Gurung
Dhanu Gurung

Reputation: 8860

I just need to comment following line in my 'config/application.rb' to solve this issue.

# config.active_record.whitelist_attributes = true

Upvotes: 0

Harish Shetty
Harish Shetty

Reputation: 64363

Add this to your base class:

  def attributes_protected_by_default
    super - [self.class.inheritance_column]
  end

I recommend Adam's method unless you are dealing with a mixed list.

Upvotes: 1

Related Questions