我正在尝试添加或删除嵌套has_many对象,如下所示
class Question < ActiveRecord::Base
has_many :comments
end
= form_for @question, :url => {:action => "create"} do |f|
= f.label :name
= f.text_field :name
#comments
= link_to 'Add Comment", add_comment_question_path, method: :get
= f.submit
:JavaScript
$('#add_comment').click(function() {
$('#comments').append("#{escape_javascript(render(:partial => "comment"))}");
});
在我的_comment.html里
= fields_for @question.comments do |c|
= c.label :msg
= c.text_field :msg
在我的控制器中
def add_comment
@question.comments << Comment.new
end
In routes.rb
resources :questions do
get :add_comment, :on => :member
end
但是我在加载question/new.html.haml
时遇到路由错误。我还运行rake routes
获取正确指定的网址。为什么我收到此错误?
我假设错误在add_comment_question_path
. 此命名路由需要将问题资源传递给它,如 add_comment_question_path(@question)
。 但这在您的情况下仍然不起作用,因为您正在尝试以相同的形式创建@question
。
你试过吗:
= form_for @question, :url => questions_path do |f|
questions_path
应从routes.rb
自动生成。这些可以通过运行rake routes
来枚举,它显示了可用的路由,然后可以用route_path
或route_url
来调用。
呵
尝试添加方法发布:
form_for(@question, :url => {:action => "create"}, :html => {:method => "post"} ) do |f|
并将routes.rb编辑为:
In routes.rb
resources :questions do
member do
get :add_comment
end
end