Rails为nil创建动作未定义方法'each':NilClass

时间:2013-09-25 21:17:19

标签: javascript jquery ruby-on-rails ruby ajax

在我的Rails应用程序中,我正在创建一个包含contentEditable div的表单,因此我必须通过AJAX“PUT”请求手动将所有数据发送到我的控制器。但是,创建操作不再有效,并抛出此错误:

Started POST "/submissions" for 98.245.21.165 at 2013-09-25 20:57:51 +0000                                                                                                
Processing by SubmissionsController#create as JSON                                                                                                                        
Parameters: {"title"=>"fyc", "content"=>"fuc", "folder_id"=>"1"}                                                                                                        
User Load (80.3ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1                                                                                        
(81.3ms)  SELECT COUNT(*) FROM "submissions" WHERE "submissions"."title" = 'fyc'                                                                                       
Completed 500 Internal Server Error in 181ms                                                                                                                              

NoMethodError (undefined method `each' for nil:NilClass):                                                                                                                 
  app/controllers/submissions_controller.rb:16:in `create'

这是我在提交控制器中的创建操作:

def create 

    ajax_title = params[:title]
    ajax_content = params[:content]
    ajax_folder = params[:folder_id]
    ajax_parent = params[:parent_id]
    ajax_children = params[:children]

    @submissions = Submission.where(title: ajax_title)

    if @submissions.empty?
    @submission = Submission.create({title: ajax_title, content: ajax_content, user_id: current_user.id, folder_id: ajax_folder, parent_id: ajax_parent, children: ajax_children})
    else
        @submissions[0].content = ajax_content
        @submissions[0].save
    end
end

第16行,其中Rails抛出NoMethodError,是if @submissions.empty?之后创建Submission实例的行。

我唯一的想法是,可能在顶部,我将params放入ajax_变量,它返回nil?我耙了我的路线,可以看到我确实有一个/submissions PUT请求路由到这个创建动作,所以这不是问题。

这是有问题的AJAX调用:

$("#save-entry").click(function(){
            $.ajax({
                type: "POST",
                url: "/submissions",
                dataType: "json",
                data: {title: $("#title-create-partial").text(), content: $("#content-create-partial").text(), folder_id: <%= @folder.id %>},
                complete: function(){
                    $.get("/ajax_load_events/", {folder: <%= @folder.id %>}, null, "script");
                }
            });
        });

就像我说的那样,我使用HTML5 contentEditable div作为表单输入,所以据我所知,我不能真正依赖Rails为我做AJAX调用。这个错误最近才开始发生,我不确定它是如何开始的。

有什么想法吗?我现在很绝望。

更新这是我的Submission.rb模型:

class Submission < ActiveRecord::Base

belongs_to :user
belongs_to :folder
belongs_to :parent, :class_name => 'Submission'
has_many :children, :class_name => 'Submission', :foreign_key => 'parent_id', :order => ('updated_at DESC')

attr_accessible :content, :title, :user_id, :folder_id, :parent_id, :children

def self.search(search)
  if search
      where('name LIKE ?', "%#{search}%")
  else
      scoped
  end
end

def attributes_with_children
  attributes.merge(children: children.map(&:attributes_with_children))
end

end

我的Folder.rb模型:

class Folder < ActiveRecord::Base
attr_accessible :title, :user_id, :parent_id

belongs_to :user
belongs_to :parent, :class_name => 'Folder'
has_many :children, :class_name => 'Folder', :foreign_key => 'parent_id'
has_many :submissions, :order => ('updated_at DESC')

def self.search(search)
where("title like ?", "%#{search}%")
end

end

1 个答案:

答案 0 :(得分:0)

因为submission has_many children然后

Submission.create(:children => nil)会抛出以下错误,因为它需要children

的数组
NoMethodError: You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.each

但是Submission.create(:children => [])不会抛出错误。

在您的示例中,params[:children]nil,因此会抛出错误。所以在控制器中你可以做到

ajax_children = Array(params[:children])
#=> [] if params[:children] is nil

这会将nil转换为[],如果参数为[1,2,3],则保持不变。

通常,确保传递给模型方法的值在控制器中的格式正确,因为用户输入可能会有很大差异。