我有一个模态形式:
<div id="commentModal" class="modal hide fade">
<div class="modal-body">
<%= form_for(Comment.new, remote: true, html: {"data-type" => :json}, :validate => true) do |f| %>
<%= f.hidden_field(:illustration_id, :value => @illustration.id) %>
<%= f.hidden_field(:user_id, :value => current_user.id) %>
<%= f.text_area(:comment, :id => "comment_message") %>
<%= f.submit "Submit", :class => 'btn btn-custom-primary' %>
<% end %>
</div>
</div>
当我提交评论两次添加到数据库时,这里是日志。你明白为什么会这样吗?我可以提供任何其他代码来提供帮助吗?
Started POST "/comments" for 127.0.0.1 at 2013-07-13 10:58:32 -0400
Processing by CommentsController#create as JSON
Parameters: {"utf8"=>"✓", "authenticity_token"=>"asdfasdfasdfasdfasasdfasdfasdfasdfasdf", "comment"=>{"illustration_id"=>"1", "user_id"=>"1", "comment"=>"Test comment"}, "commit"=>"Submit"}
(36.8ms) BEGIN
SQL (78.6ms) INSERT INTO "comments" ("comment", "created_at", "illustration_id", "updated_at", "user_id") VALUES ($1, $2, $3, $4, $5) RETURNING "id" [["comment", "Test comment"], ["created_at", Sat, 13 Jul 2013 14:58:32 UTC +00:00], ["illustration_id", 1], ["updated_at", Sat, 13 Jul 2013 14:58:32 UTC +00:00], ["user_id", 1]]
(38.7ms) COMMIT
Completed 201 Created in 163ms (Views: 1.4ms | ActiveRecord: 154.1ms)
Started POST "/comments" for 127.0.0.1 at 2013-07-13 10:58:32 -0400
Processing by CommentsController#create as JSON
Parameters: {"utf8"=>"✓", "authenticity_token"=>"asdfasdfasdfasdfasasdfasdfasdfasdfasdf", "comment"=>{"illustration_id"=>"1", "user_id"=>"1", "comment"=>"Test comment"}, "commit"=>"Submit"}
(36.5ms) BEGIN
SQL (36.9ms) INSERT INTO "comments" ("comment", "created_at", "illustration_id", "updated_at", "user_id") VALUES ($1, $2, $3, $4, $5) RETURNING "id" [["comment", "Test comment"], ["created_at", Sat, 13 Jul 2013 14:58:32 UTC +00:00], ["illustration_id", 1], ["updated_at", Sat, 13 Jul 2013 14:58:32 UTC +00:00], ["user_id", 1]]
(38.3ms) COMMIT
Completed 201 Created in 116ms (Views: 0.9ms | ActiveRecord: 111.7ms)
根据要求,评论控制器创建方法:
def create
@comment = Comment.new(params[:comment])
respond_to do |format|
if @comment.save
format.html { redirect_to @comment, notice: 'Comment was successfully created.' }
format.json { render json: @comment, status: :created, location: @comment }
else
format.html { render action: "new" }
format.json { render json: @comment.errors, status: :unprocessable_entity }
end
end
end
和新方法:
def new
@comment = Comment.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @comment }
end
end