我想通过ajax调用提交一些表单,并且我编写了以下代码但是我得到错误未定义的方法`model_name'对于Hash:Class
<%= form_for :url=>articles_editcomment_path ,:method=>:post ,:remote => true do |f| %>
<p>
<%= f.label :body %><br>
<%= f.text_area :body %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
如何克服错误?
答案 0 :(得分:0)
您没有提及表单的模型或变量:
<%= form_for :article, :url=>articles_editcomment_path ,:method=>:post ,:remote => true do |f| %>
上述方法不需要Article
类型的变量,也不会在编辑模式下填充表单。
或强>
<%= form_for @article, :url=>articles_editcomment_path ,:method=>:post ,:remote => true do |f| %>
上面的方法需要一个名为@article
的变量,它可以在控制器中初始化,并在编辑模式下填充表单。
如果这没有解决问题,请随时提出更多
答案 1 :(得分:0)
您遇到的问题是您正在使用form_for
而不传递ActiveRecord对象 - 这就是您的错误显示如下原因:
未定义的方法`model_name'用于Hash:Class
注意您传递给form_for
方法的内容 - 哈希。
-
应该做的是使用ActiveRecord对象填充表单。这就是Rails 使用form_for
构建 ActiveRecord表单的方式 - 它从对象本身获取数据&amp;然后在它背后构建表格
为了解决您的问题,需要使用ActiveRecord对象填充表单:
#app/controllers/comments_controller.rb
Class CommentsController < ApplicationController
def edit
@article = Article.find params[:article_id]
@comment = Comment.find params[:id]
end
end
#app/views/comments/edit.html.erb
<%= form_for [@article, @comment] do |f| %>
...
<% end %>