2016-02-05 75 views
0

我有一个应用程序中,我想创建嵌套形式Rails的嵌套形式创作

我的模型:

class Abonent < ActiveRecord::Base 
    belongs_to :town 
    has_many :numbers, :dependent => :destroy 

    accepts_nested_attributes_for :numbers 
end 

class Number < ActiveRecord::Base 
    belongs_to :abonent 
end 

Abonents控制器:

class AbonentsController < ApplicationController 


def new 
    @abonent = Abonent.new 
end 

def create 
    @abonent = Abonent.new abonents_params 
    if @abonent.save 
     redirect_to :towns 
    else 
     render action: "new" 
    end 
end 

private 

def abonents_params 
    params.require(:abonents).permit(:fullname, :work_position, :department, :email, :town_id, numbers_attributes: [ :phone ]) 
end 

end 

而且abonents查看

<hr><br> 

<%= form_for :abonents, url: abonents_path do |f| %> 
    <%= f.label :fullname %>: 
    <%= f.text_field :fullname %><br /> <br /> 

    <%= f.label :work_position %>: 
    <%= f.text_field :work_position %><br /><br /> 

    <%= f.label :department %>: 
    <%= f.text_field :department %><br /><br /> 

    <%= f.label :email %>: 
    <%= f.text_field :email %><br /><br /> 

    <%= f.label :town_id %>: 
    <%= f.select :town_id, Town.all.collect { |p| [ p.ru_name, p.id ] } %><br /><br /> 

    <%= f.fields_for :numbers do |phones|%> 
    <%= phones.label :phone %>: 
    <%= phones.text_field :phone %><br /><br /> 

    <% end %> 


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

问题是当我提交表单,它会创建abonent,但不会为此abonent创建号码。

我看到了很多不同的手册,在我的代码中找不到错误。 请帮忙。 谢谢。

UPD我在github上为这个问题添加了一个repo

回答

1

您需要build相关的记录

def new 
    @abonent = Abonent.new 
    @abonent.numbers.build 
end 
+0

新增'@ abonent.numbers.build'现在。没有任何改变。 – OmBird

+0

@OmBird也尝试改变'<%= form_for:abonents,url:abonents_path do | f | %>'到'<%= form_for @abonent do | f | %>' – Pavan

+2

我改变了这一点。在那之后,rails向我展示了一个错误'param丢失或者值为空:abonents'。我搜索了这个错误并将'params.require(:abonents).permit(:fullname,:work_position,:department,:email,:town_id,numbers_attributes:[:id,:phone])'改为'params.require(: abonent).permit(:fullname,:work_position,:department,:email,:town_id,numbers_attributes:[:id,:phone])''。 它的工作!非常感谢!你是我的英雄=) – OmBird