我有两个模型页面和作者,这里是模型页面的代码:
现在我的模型如下:
class Page < ActiveRecord::Base
validates :title, :presence => true
belongs_to :author
end
作者模型:
class Author < ActiveRecord::Base
has_many :pages
end
我的表格如下:
<%= form_for(@page) do |f| %>
<% if @page.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@page.errors.count, "error") %> prohibited this post from being saved:</h2>
<ul>
<% @page.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<p>
<%= f.label :title %><br />
<%= f.text_field :title %>
</p>
<p>
<%= f.label :body %><br />
<%= f.text_area :body %>
</p>
<p>
<%= f.fields_for :author do |fields| %>
<%= f.label :author %><br />
<%= fields.text_field :author %>
<% end %>
</p>
<p>
<%= f.label :email %><br />
<%= f.text_field :email %>
</p>
<p>
<%= f.label :reference %><br />
<%= f.select(:reference,[['google',1],['yahoo',2],['MSN',3],['Ask',4]]) %>
</p>
<%= f.submit "Submit" %>
<% end %>
和控制器:
class PagesController < ApplicationController
def index
@total = Page.count
@pages = Page.find(:all)
end
def show
@page = Page.find(params[:id])
end
def new
@page = Page.new
end
def create
@page = Page.new(params[:page])
if @page.save
redirect_to pages_path, :notice => "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模型中,还有一个问题,那么该字段根本不显示。我真的想完成这个......任何帮助?
答案 0 :(得分:1)
显然,这与关联无关。对不起,我很抱歉。您可以执行以下操作,但是您的页面控制器正在对作者执行操作,这不太合适。您可以创建一个作者控制器,并包括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 %>