2012-05-09 61 views
3

我正在處理一個簡單的項目來測試Rails 3.2的嵌套屬性。無法將符號轉換爲Integer + 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

不告訴我們錯誤發生的位置,即代碼的哪一行和哪一行,我們將無法爲您提供幫助。一個完整的堆棧跟蹤也有幫助。 –

+0

Holger就是對的,我們需要一個完整的stacktrace和你的posts_controller的創建方法來幫助你 –

回答

4

我同意,這是艱難的排查沒有堆棧跟蹤和創建方法的意見,但表示,這看起來奇怪:

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

字段對於你的comment對象,對吧?而不是後對象的comment_attributes(後者在這裏沒有意義,至少在一讀時)。

您可以嘗試更改:comments_attributes:comments

+0

謝謝史蒂夫。它現在正在工作,包括嵌套模型的驗證。 :-) – Ben

+0

爲什麼我試着從:comments_attributes更改爲:評論,然後text_field不顯示在用戶界面上。 – hainguyen