我试图通过将响应从create移动到视图来清理代码(使用了一些帮助程序,这很有意义)。但是出于某种原因,我的js回调永远不会被调用。我100%困惑,所以这里是我的日志和代码。非常感谢: - )
def create
@review = Review.new(post_params)
@review.library = @library if @library
@review.user = current_user
if !@review.save
render json: {error_code: "400", message: "Invalid paramaters"}
end
respond_to do |format|
format.html {redirect_to(library_path(@library))}
format.json {render "create.json"}
end
end
$(document).ready( function(){
$("#new_review").submit(function(event) {
event.preventDefault();
var form = $(this);
var values = form.serialize();
var url = form.attr("action");
debugger;
$.post(url + ".json", values).done(function(data) {
debugger;
});
});
});
{
review: <%= @review.to_json %>,
average_rating: <%= number_to_human(@library.average_rating) %>
}
Started POST "/libraries/10/reviews.json" for 127.0.0.1 at 2017-07-16 10:12:18 -0400
Processing by ReviewsController#create as JSON
Parameters: {"utf8"=>"✓", "authenticity_token"=>"MgB1pj2lQNMgPCknUMP+lc2EWtrp06n1GkaAbrJONJwM//fmY7gI8azvy3IFh9NZfoRysoiVln3vAH+AFzW1QQ==", "review_rating_dispaly"=>"1", "review"=>{"rating"=>"1", "comment"=>""}, "library_id"=>"10"}
Library Load (0.2ms) SELECT "libraries".* FROM "libraries" WHERE "libraries"."id" = ? LIMIT 1 [["id", 10]]
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT 1 [["id", 1]]
(0.1ms) begin transaction
SQL (0.3ms) INSERT INTO "reviews" ("comment", "library_id", "user_id", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?) [["comment", ""], ["library_id", 10], ["user_id", 1], ["created_at", "2017-07-16 14:12:18.075609"], ["updated_at", "2017-07-16 14:12:18.075609"]]
(5.6ms) commit transaction
(0.1ms) SELECT AVG("reviews"."rating") FROM "reviews" WHERE "reviews"."library_id" = ? [["library_id", 10]]
Rendered reviews/create.json.erb (1.8ms)
Completed 200 OK in 16ms (Views: 4.2ms | ActiveRecord: 6.4ms)
来自Chrome网络日志中服务器的{
review: {"id":37,"rating":1,"user_id":1,"library_id":10,"comment":"","created_at":"2017-07-16T14:23:25.213Z","updated_at":"2017-07-16T14:23:25.213Z"},
average_rating: 1.86
}
答案 0 :(得分:0)
在行定义之前添加"
,并将.html_safe
添加到json
{
"review": <%= @review.to_json(only: [:comment, :rating]).html_safe %>,
"average_rating": <%= number_to_human(@library.average_rating) %>
}