【问题标题】:can't convert Symbol into Integer + Rails 3.2 Nested Attributes无法将符号转换为整数 + Rails 3.2 嵌套属性
【发布时间】:2012-05-09 11:22:00
【问题描述】:

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

【问题讨论】:

  • 如果不告诉我们错误发生在哪里,即代码的哪一行和文件中,我们将无法为您提供帮助。完整的堆栈跟踪也有帮助。
  • Holger 是对的,我们需要一个完整的堆栈跟踪和您的 posts_controller 的 create 方法来帮助您

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


【解决方案1】:

我同意 cmets 的观点,即如果没有 stacktrace 和 create 方法很难进行故障排除,但话虽如此,这看起来很奇怪:

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

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

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

【讨论】:

  • 谢谢史蒂夫。它现在正在工作,包括对嵌套模型的验证。 :-)
  • 为什么我尝试从 :cmets_attributes 更改为 :cmets 然后 text_field 不会显示在 UI 上。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-03
  • 2011-08-30
  • 1970-01-01
  • 2012-01-09
相关资源
最近更新 更多