rails 3中嵌套模型的部分forms

我有两个模型页面和作者,这里是模型页面的代码:

编辑-1

现在我的模特如下:

class Page  true belongs_to :author end 

作者模型:

 class Author < ActiveRecord::Base has_many :pages end 

我的表格如下:

    

prohibited this post from being saved:






和控制器:

 class PagesController  "The data has been saved!" else render "new" end end def edit @page = Page.find(params[:id]) end def update @page = Page.find(params[:id]) if @page.update_attributes(params[:page]) redirect_to pages_path, :notice => "Your post has been updated!" else render "edit" end end def destroy @page = Page.find(params[:id]) @page.destroy redirect_to pages_path, :notice => "Your page has been deleted!" end end 

现在,当我提交表单时,它给了我这个错误:

 ActiveRecord::AssociationTypeMismatch in PagesController#create Author(#40328004) expected, got ActiveSupport::HashWithIndifferentAccess(#32291496) Rails.root: C:/rorapp Application Trace | Framework Trace | Full Trace app/controllers/pages_controller.rb:19:in `new' app/controllers/pages_controller.rb:19:in `create' Request Parameters: {"utf8"=>"✓", "authenticity_token"=>"hzBlXsdUjEDDCLp036R8bJBwep6BdATSvJPNwt0M8Dg=", "page"=>{"title"=>"", "body"=>"", "author"=>{"author"=>""}, "email"=>"", "reference"=>"1"}, "commit"=>"Submit"} Show session dump Show env dump Response Headers: None 

还有一个问题,如果我将accepts_nested_attributes_for :author添加到我的Page模型,那么该字段根本不会显示。 我真的想要完成这个……任何帮助?

显然,这与协会不起作用。 对不起,我很抱歉。 您可以执行以下操作,但随后您的页面控制器正在对作者执行操作,这不太合适。 您可以创建一个作者控制器,并包括fields_for:pages,以便同时创建作者和第一个页面。

 class PagesController < ApplicationController def new @author = Author.new @page = @author.pages.new end def create @author = Author.create(params[:author]) end end class Author < ActiveRecord::Base has_many :pages accepts_nested_attributes_for :pages end class Page < ActiveRecord::Base belongs_to :author end <%= form_for(@author, :url => pages_url) do |f| %> <%= f.text_field :author %> <%= f.fields_for :pages do |fields| %> <%= fields.text_area :body %> <% end %> <% end %>