0
我正在嘗試創建一個用戶可以評論的產品頁面。問題是頁面被重新加載,就好像沒有javascript一樣。 其實要求是HTML(我認爲)AJAX中的請求無效。頁面重新加載
評論控制器:
class CommentsController < ActionController::Base
def create
@product = Product.find(params[:product_id])
@comment = Comment.new(params_comment)
@comment.product = @product
respond_to do |format|
if @comment.save
format.js
format.html { redirect_to @product }
else
render :new
end
end
end
private
def params_comment
params.require(:comment).permit(:body)
end
end
在產品顯示:
<% unless @comments.empty? %>
<h1> Comments </h1>
<div id="comments">
<% @comments.each do |comment| %>
<%= render comment %>
<% end %>
</div>
<% end %>
<%= form_for @comment, url: comments_path, method: :create, format: :js, remote: true do |f| %>
<%= hidden_field_tag "product_id", @product.id%>
<div class="field">
<%= f.text_area :body, :size => "25x1", :placeholder => "Comment here..."%>
</div>
<%= f.submit "Comment" %>
<% end %>
的_comment.html.erb
<p><%= comment.body %></p>
而且最後是create.js.erb
$("#comments").append("<%= escape_javascript(render @comment) %>");
當我創建新產品時,沒有javascript請求。 在控制檯我得到:
Started POST "/comments" for 127.0.0.1 at 2014-02-19 20:38:29 +0200
Processing by CommentsController#create as HTML
Parameters: {"utf8"=>"✓", "product_id"=>"1", "comment"=>{"body"=>"asdas"}, "commit"=>"Comment"}
Product Load (0.3ms) SELECT "products".* FROM "products" WHERE "products"."id" = ? LIMIT 1 [["id", "1"]]
(0.1ms) begin transaction
SQL (0.7ms) INSERT INTO "comments" ("body", "created_at", "product_id", "updated_at") VALUES (?, ?, ?, ?) [["body", "asdas"], ["created_at", Wed, 19 Feb 2014 18:38:29 UTC +00:00], ["product_id", 1], ["updated_at", Wed, 19 Feb 2014 18:38:29 UTC +00:00]]
(4.8ms) commit transaction
Redirected to http://localhost:3000/products/1
Completed 302 Found in 12ms (ActiveRecord: 5.9ms)
在此先感謝!
編輯:
我忘了,在我的佈局已經包含:
<%= javascript_include_tag "application", "data-turbolinks-track" => true %>
<%= csrf_meta_tags %>
編輯2
這是由形式生成的HTML代碼:
<form accept-charset="UTF-8" action="/comments" class="new_comment" data-remote="true" id="new_comment" method="post"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓" /><input name="_method" type="hidden" value="create" /></div>
<input id="product_id" name="product_id" type="hidden" value="1" />
<div class="field">
<textarea cols="25" id="comment_body" name="comment[body]" placeholder="Comment here..." rows="1">
</textarea>
</div>
<input name="commit" type="submit" value="Comment" />
</form>
您可以**查看您的產品展示頁面的源代碼**並向我顯示由'form_for'生成的HTML'
我編輯過。非常感謝你! – hcarreras
我沒有看到你在哪裏使用AJAX。你能說明你是如何攔截提交動作並嘗試進行AJAX調用嗎? –