1

当我尝试提交下面的表格时,我收到了这个错误WARNING: Can't mass-assign protected attributes: sub_category。我试图在 stackoverflow 上解决以前提出的相关问题,似乎我在正确的轨道上,但由于某种原因,我仍然遇到同样的错误,什么是我做错了吗?我已经包含了下面的所有信息,提前谢谢你。

查看/表格

 <%= 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%>

控制器

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     

楷模

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
4

1 回答 1

1

您应该使用f.fields_for :sub_categories(关联名称)。

并且不要忘记在渲染表单之前建立关联:

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

rubyonrails api :: fields_for

于 2012-04-25T19:47:42.337 回答