我试图允许用户在Rails中使用AJAX在特定的帖子上创建注释。我得到了要显示的表单,但是在创建时它不起作用。在我的形式中,它是href=“/post/post_id/注释/新的”method="post“。我认为应该是post/post_id/ method="post“注释,但我无法让它工作。
控制台只是说没有路由匹配post/id/comments/new,因为它显然是错误的。
comments_controller.rb
class CommentsController < ApplicationController
respond_to :html, :js
def index
@comments = Comment.all
end
def new
@new_comment = Comment.new
end
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.create(comment_params)
end注释视图中的_form.html.erb
<%= simple_form_for post_comments_path, remote: true, html:{class: 'form-inline'} do |f| %>
<%= f.input :body, input_html: { class: 'form-control' } %>
<%= f.button :submit, :class => "btn btn-success", value: "Post Comment" %>
<% end %>index.html.erb (带有帖子的主视图)
<div class="pull-left">
<%= link_to new_post_comment_path(post), remote: true, method: :get do %>
<button class="btn btn-primary">+Comment</button>
<% end %>
</div>
<div id="comment-form" style="display:none;"></div>
<% if post.comments.count > 0 %>
<div id="comments"><%= render @comments %></div>
<% end %>评论中的new.js.erb
$('#comment-form').html("<%= j (render 'form') %>");
$('#comment-form').slideDown(350);评论中的create.js.erb
$('#comments').html("<%= j (render @comments) %>");
$('#comment-form').slideUp(350);发布于 2015-03-05 15:08:43
您不应该将路径助手传递给form_for助手。给它一个模型,它会自动生成正确的url。试试这个:
<%= simple_form_for @new_comment, remote: true, html:{class: 'form-inline'} do |f| %>
<%= f.input :body, input_html: { class: 'form-control' } %>
<%= f.button :submit, :class => "btn btn-success", value: "Post Comment" %>
<% end %>更新:似乎是在使用嵌套资源。在这种情况下,您将需要调整您的#新控制器方法。
def new
@post = Post.find(params[:post_id])
@new_comment = Comment.new
end然后将@post和@new_comment传递给form_for。同样,这应该足以让Rails知道在哪里发布表单。
<%= simple_form_for [@post, @new_comment], remote: true, html:{class: 'form-inline'} do |f| %>
<%= f.input :body, input_html: { class: 'form-control' } %>
<%= f.button :submit, :class => "btn btn-success", value: "Post Comment" %>
<% end %>更新:您在create.js.erb中有一个错误,@注释没有定义,它应该是单数:@还确保您实际上有_comment分部:)
$('#comments').html("<%= j (render @comment) %>");
$('#comment-form').slideUp(350);发布于 2015-03-05 15:11:13
由于您试图通过表单将注释绑定到帖子,因此需要将@post传递到路径中。所以看起来是:
在阅读了下面的评论后更新了:
<%= simple_form_for [@post, @new_comment], remote: true, html:{class: 'form-inline'} do |f| %>
<%= f.input :body, input_html: { class: 'form-control' } %>
<%= f.button :submit, :class => "btn btn-success", value: "Post Comment" %>
<% end %>注意到@post了吗?这就是为什么路径呈现错误的原因。
https://stackoverflow.com/questions/28880952
复制相似问题