如何设置我的 Rails 表单以提交到创建方法?
How do I set up my Rails form to submit to a create method?
我正在使用 Rails 5,但对如何设置表单以便它提交到我的 "create" 控制器方法感到困惑。这是我设置的路线
resources :comments
这是我设置的表格
<%= form_for @comments, :html => {:class => "commentsForm"} do |f| %>
<div class="field">
<%= f.label :description %><br>
<%= f.text_field :description %>
</div>
<%= recaptcha_tags %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
但是上面的代码死于错误
undefined method `comments_index_path' for #<#<Class:0x00007fdaaf2b6240>:0x00007fdaaf2ae518>
我不确定我还应该做些什么才能让我的表格正常工作。在我的控制器中,我有一个 "create" 和一个 "new" 方法。
编辑:这是控制器
class CommentsController < ActionController::Base
before_action :require_current_user, except: [:new]
def new
@comments = Comments.new
end
def create
@comments = Comments.new(params[:comments].permit(:description))
if verify_recaptcha(model: @comments)
render "Finished"
end
end
end
我想,你的申请comments_controller新动作应该是这样的-
# app/controllers/comments_controller.rb
class CommentsController < ApplicationController
# Rest of code here
def new
@comment = Comment.new # Not the @comments
end
# Rest of code here
end
你的部分表格应该是这样的
# app/views/comments/_form.html.erb
<%= form_for @comment, :html => {:class => "commentsForm"} do |f| %>
<div class="field">
<%= f.label :description %><br>
<%= f.text_field :description %>
</div>
<%= recaptcha_tags %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
我正在使用 Rails 5,但对如何设置表单以便它提交到我的 "create" 控制器方法感到困惑。这是我设置的路线
resources :comments
这是我设置的表格
<%= form_for @comments, :html => {:class => "commentsForm"} do |f| %>
<div class="field">
<%= f.label :description %><br>
<%= f.text_field :description %>
</div>
<%= recaptcha_tags %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
但是上面的代码死于错误
undefined method `comments_index_path' for #<#<Class:0x00007fdaaf2b6240>:0x00007fdaaf2ae518>
我不确定我还应该做些什么才能让我的表格正常工作。在我的控制器中,我有一个 "create" 和一个 "new" 方法。
编辑:这是控制器
class CommentsController < ActionController::Base
before_action :require_current_user, except: [:new]
def new
@comments = Comments.new
end
def create
@comments = Comments.new(params[:comments].permit(:description))
if verify_recaptcha(model: @comments)
render "Finished"
end
end
end
我想,你的申请comments_controller新动作应该是这样的-
# app/controllers/comments_controller.rb
class CommentsController < ApplicationController
# Rest of code here
def new
@comment = Comment.new # Not the @comments
end
# Rest of code here
end
你的部分表格应该是这样的
# app/views/comments/_form.html.erb
<%= form_for @comment, :html => {:class => "commentsForm"} do |f| %>
<div class="field">
<%= f.label :description %><br>
<%= f.text_field :description %>
</div>
<%= recaptcha_tags %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>