我正在开发一个简单的项目来测试Rails 3.2的嵌套属性。但是,我在尝试提交表单时遇到了这种错误:
can't convert Symbol into Integer
post.rb和comment.rb
class Post < ActiveRecord::Base
attr_accessible :title, :comments_attributes
has_many :comments
accepts_nested_attributes_for :comments
validates_presence_of :title
end
class Comment < ActiveRecord::Base
attr_accessible :comment, :author
belongs_to :post
validates_presence_of :comment
validates_presence_of :author
end
posts_controller.rb
def new
@post = Post.new
@post.comments.build
respond_to do |format|
format.html # new.html.erb
format.json { render json: @post }
end
end
_form.html.erb
<%= form_for(@post) do |f| %>
<% if @post.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2>
<ul>
<% @post.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :title %><br />
<%= f.text_field :title %>
</div>
<%= f.fields_for :comments_attributes do |builder| %>
<fieldset>
<%= builder.label :comment %><br />
<%= builder.text_field :comment %><br />
<%= builder.label :author %><br />
<%= builder.text_field :author %>
</fieldset>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
参数
{"utf8"=>"✓",
"authenticity_token"=>"gNA0mZMIxkA+iIJjw8wsddcKxvmzaFnrgiHvFw1OrYA=",
"post"=>{"title"=>"Dummy Title",
"comments_attributes"=>{"comment"=>"Dummy Comment",
"author"=>"Dummy Author"}},
"commit"=>"Create Post"}
答案 0 :(得分:4)
我同意这些评论说没有stacktrace和create方法很难排除故障,但是说,这看起来很奇怪:
<%= f.fields_for :comments_attributes do |builder| %>
这些字段适用于comment
个对象,对吧?而不是帖子对象的comment_attributes
(后者在这里没有意义,至少在第一次阅读时)。
您可以尝试将:comments_attributes
更改为:comments
。