2013-12-18 72 views
0

我試圖創建一個單一的形式允許創建評論和相關的附件Rails的accepts_nested_attributes給未定義的方法

評論型號有:

class Comment < ActiveRecord::Base 
    has_many :attachments 
    accepts_nested_attributes_for :attachments  
end 

評論控制器有:

# GET /comments/new 
    # GET /comments/new.json 
    def new 
    @comment = Comment.new 
    @worequest = params[:worequest_id] 

    respond_to do |format| 
     format.html # new.html.erb 
     format.json { render json: @comment } 
    end 
    end 

在意見表,我想補充一點:

<%= simple_form_for @comment, :html => {:class => 'form-horizontal'} do |f| %> 
    (CODE FOR COMMENT) 
    <% f.fields_for @attachments do |builder| %> 
    <%= builder.input :name, :label => 'Attachment Name' %> 
    <%= builder.file_field :attach, :label => 'Attachment File' %> 
    <% end %> 

但是,我得到這個錯誤:

undefined method `model_name' for NilClass:Class 

感謝您的幫助!

+1

您在'simple_form_for'中使用的'@ comment'對象是'nil'。請發佈您的控制器代碼。 – vee

+1

您未定義@attachments – Donovan

回答

1

由於@Donovan評論說,你沒有定義@attachments,因此錯誤。我猜想錯誤來自form_for聲明。

更新您的控制器new動作的代碼來構建附件上@comment

# GET /comments/new 
    # GET /comments/new.json 
    def new 
    @comment = Comment.new 
    @comment.attachments.build # Add this line 

    @worequest = params[:worequest_id] 

    respond_to do |format| 
     format.html # new.html.erb 
     format.json { render json: @comment } 
    end 
    end 

然後更新您的表單視圖代碼:

<%= simple_form_for @comment, :html => {:class => 'form-horizontal'} do |f| %> 
    (CODE FOR COMMENT) 
    <%= f.fields_for :attachments do |builder| %> 
    <%= builder.input :name, :label => 'Attachment Name' %> 
    <%= builder.file_field :attach, :label => 'Attachment File' %> 
    <% end %> 

你也可以選擇在你的控制器動作來定義@attachments和改爲在你的視圖中使用它。通過做f.fields_for :attachments,使用當前對象(在這種情況下爲@comment)附件關聯,因此在控制器中定義@attachments是不必要的。

+0

感謝您的幫助。我將該行添加到控制器。我沒有看到任何形式上的差異。而且我仍然得到'未定義的方法model_name NilClass' – Reddirt

+0

@Reddirt,你能否確認你更新了視圖。你也可以發佈跟蹤到你的問題。 – vee

+0

我的錯誤 - 沒有看到表單中的變化。 – Reddirt