ruby - 无法将 Symbol 转换为 Integer + Rails 3.2 嵌套属性

标签 ruby ruby-on-rails-3 forms nested-attributes

我正在做一个简单的项目来测试 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"}

最佳答案

我同意没有堆栈跟踪和创建方法很难排除故障的评论,但话虽如此,这看起来很奇怪:

 <%= f.fields_for :comments_attributes do |builder| %>

这些字段用于您的 comment 对象,对吗?与 post 对象的 comment_attributes 相反(后者在这里没有意义,至少在第一次阅读时是这样)。

您可以尝试将 :comments_attributes 更改为 :comments

关于ruby - 无法将 Symbol 转换为 Integer + Rails 3.2 嵌套属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10515078/

相关文章:

ruby - 在 ubuntu 上安装 rvm 的问题

Ruby 递归返回结果问题

ruby-on-rails - 将参数传递给 '.js.erb' 模板

database - 建模用户、组和成员数据库表

javascript - 即使正在检查其中一个 radio ,表单仍然返回 false

c# - 线程启动期间的竞争条件?

php - Jquery AJAX 成功但未给出响应

ruby - 在 AWS Linux 上增加 RestClient/Net::HTTP 中的 connect(2) 超时

ruby-on-rails-3 - 您通过了 :github as an option for gem 'spree_gateway' , 但它无效

javascript - js 或等于运算符相当于 ruby​​ 中的运算符