在我的 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 实例之后的行。
我唯一的想法是,也许在我将参数放入 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