2012-10-18 33 views
0

在深入研究ruby的嵌套模型时,遇到了一个问题。嵌套模型/表单不创建条目

考虑以下情形,

我有以下型号:

  • 作者

以下规格:

作者:

class Author < ActiveRecord::Base 
    attr_accessible :name 
    has_many :books, dependent: :destroy 

    accepts_nested_attributes_for :books #I read this is necessary here: http://stackoverflow.com/questions/12300619/models-and-nested-forms 

    # and some validations... 
end 

书:

class Book < ActiveRecord::Base 
    attr_accessible :author_id, :name, :year 
    belongs_to :author 

    #and some more validations... 
end 

我想一本书添加到作者。这里是我的authors_controller:

def new_book 
    @author = Author.find(params[:id]) 
end 

def create_book 
    @author = Author.find(params[:id]) 
    if @author.books.create(params[:book]).save 
    redirect_to action: :show 
    else 
    render :new_book 
    end 
end 

这是我尝试做它的形式:

<h1>Add new book to <%= @author.name %>'s collection</h1> 
<%= form_for @author, html: { class: "well" } do |f| %> 
    <%= fields_for :books do |b| %> 
     <%= b.label :name %> 
     <%= b.text_field :name %> 
     <br/> 
     <%= b.label :year %> 
     <%= b.number_field :year %> 
    <% end %> 
    <br/> 
    <%= f.submit "Submit", class: "btn btn-primary" %> 
    <%= f.button "Reset", type: :reset, class: "btn btn-danger" %> 
<% end %> 

问题: 当我在数据类型,然后单击“提交”它甚至会将我重定向到正确的作者,但它不会为该作者保存新的记录。 经过大量的研究,我似乎无法找到我在这里做错了什么。

回答

1

更改authors_controller到:

def new_book 
    @author = Author.find(params[:id]) 
    @book = Book.new 
end 

您的形式:

<h1>Add new book to <%= @author.name %>'s collection</h1> 
<%= form_for ([@author, @book]), html: { class: "well" } do |f| %> 

而且,routes.rb中

resources :authors do 
    resources :books 
end 
+0

显然,改变了我的路由机制......现在它给了我'未定义的方法\'author_books_path''并引用表格的第二行... – weltschmerz

+0

请参阅http://blog.dominicsayers.com/2011/08/24/howto-create-a-simple -parent-child-form-in-rails-3-1 /从头开始具有子窗体实现。 –

+0

太棒了,谢谢!该链接解决了它:-) – weltschmerz

1

你错过了几件事情。

控制器:

... 
def new_book 
    @author = Author.find(params[:id]) 
    @author.books.build 
end 
... 

认为,这是f.fields_for并不仅仅是fields_for

<%= f.fields_for :books do |b| %> 
    <%= b.label :name %> 
    <%= b.text_field :name %> 
    <br/> 
    <%= b.label :year %> 
    <%= b.number_field :year %> 
<% end %> 
+0

这看起来更好,但现在它要求我在书籍控制器中创建方法 - 任何想法为什么? – weltschmerz

1

您还需要在您的作者模型访问的方法添加:nested_attributes_for_books。您创建控制器的创建方法不需要任何代码添加即可开始。

注:您可以设置图书控制器来渲染“书#秀”上的成功。如果应用程序将您重定向到作者,那意味着作者控制器正在处理本书的创建,除非您将其设置为重定向到作者而不是本书。