Search code examples
ruby-on-railsruby-on-rails-3ruby-on-rails-3.1mass-assignment

I get the warning "Can't mass-assign protected attributes"


When i try to submit the form below i get this error WARNING: Can't mass-assign protected attributes: sub_category.I have tried to go over previous asked related questions here on stackoverflow and seems like i am in the right track ,but for some reason i am still getting the same error,what am i doing wrong?.I have included all the info below, thank you in advance.

View/form

 <%= form_for @ip ,:url=>{:action =>"create"} do |f| %>
 <%=f.text_field   :email %>
 <% f.text_field :ip_address %>
      <%= f.fields_for :sub_category do |s| %>
      <%=s.text_field :name%>
      <%end%>
 <%=f.submit "submit" %>
 <%end%>

Controller

def create
@ips=Ip.new(params[:ip])
    @ip=@ips.sub_categories.build 
if @ip.save
    redirect_to :controller=>"home" ,:action=>"index"
else
    render 'index'
end     

Models

class Ip < ActiveRecord::Base
has_many :sub_categories ,:through=>:ip_subs
has_many :ip_subs
accepts_nested_attributes_for :sub_categories 
attr_accessible :sub_categories_attributes,:ip_address,:email,:ip_count
end

class SubCategory < ActiveRecord::Base
has_many :ip ,:through=>:ip_subs
has_many :ip_subs
end

class IpSub < ActiveRecord::Base
belongs_to :ip
belongs_to :sub_category
end

Solution

  • You should use f.fields_for :sub_categories (association name).

    And don't forget to build association before render the form:

    # in controller
    def new
      @ip = Ip.new
      @ip.sub_categories.build
    end
    

    rubyonrails api :: fields_for