所以我创建了一个表单来为我的“项目”创建“评论”。我有它工作正常,但决定通过Railscasts的信息实现ajax。现在表单似乎提交但其内容不保存在我的数据库中。我试图让评论表单提交然后重新呈现评论。谢谢!
我的终端输出:
Processing by CommentsController#create as JS
Parameters: {"utf8"=>"✓", "comment"=>{"content"=>"Cat dog"}, "commit"=>"Post", "project_id"=>"29"}
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 ORDER BY "users"."id" ASC LIMIT 1
Project Load (0.1ms) SELECT "projects".* FROM "projects" WHERE "projects"."id" = ? ORDER BY created_at DESC LIMIT 1 [["id", 29]]
Comment Load (0.2ms) SELECT "comments".* FROM "comments" WHERE "comments"."project_id" = ? LIMIT 30 OFFSET 0 [["project_id", 29]]
Rendered collection (0.0ms)
Rendered comments/create.js.erb (1.5ms)
Completed 200 OK in 44ms (Views: 40.1ms | ActiveRecord: 0.4ms)
评论创建表单
<%= form_for([@project, @comment], remote: true) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<div class="field">
<%= f.text_area :content, placeholder: "Comment...?" %>
</div>
<%= f.submit "Post", class: "btn btn-primary" %>
<% end %>
评论控制器
def create
@project = Project.find(params[:project_id])
@comment = @project.comments.build(comment_params.merge(
:user_id => current_user.id))
@comments = @project.comments.paginate(page: params[:page])
respond_to do |format|
if @comment.save
format.html { redirect_to project_url(@project) }
format.js
end
end
end
create.js
$("#comments").html("<%= escape_javascript(render(@comments)) %>");
$('#new-comment').remove();
$('#add-comment').show();
Addiitonal HTML
<div>
<% if @project.comments.any? %>
<h4>Comments (<%= @project.comments.count %>)</h4>
<ol class="comments">
<%= render @comments %>
</ol>
<%= will_paginate @comments %>
<% end %>
</div>