Javascript Rails 4、Ajax导致404和500错误
我正在学习Michael Hartl的Rails教程,,在完全按照指导学习了他的教程之后,我遇到了一个奇怪的404/500错误 我对这个错误了解得不够,不知道如何修复它 尝试从标准跟随和取消跟随按钮切换到启用Ajax的跟随/取消跟随按钮时,会发生此错误 follow按钮只会重复产生500个错误。(见图) 单击以下按钮后,服务器控制台如下所示:Javascript Rails 4、Ajax导致404和500错误,javascript,ajax,ruby-on-rails-4,http-status-code-404,Javascript,Ajax,Ruby On Rails 4,Http Status Code 404,我正在学习Michael Hartl的Rails教程,,在完全按照指导学习了他的教程之后,我遇到了一个奇怪的404/500错误 我对这个错误了解得不够,不知道如何修复它 尝试从标准跟随和取消跟随按钮切换到启用Ajax的跟随/取消跟随按钮时,会发生此错误 follow按钮只会重复产生500个错误。(见图) 单击以下按钮后,服务器控制台如下所示: Started POST "/relationships" for ::1 at 2015-11-21 10:42:41 -0500 Processin
Started POST "/relationships" for ::1 at 2015-11-21 10:42:41 -0500
Processing by RelationshipsController#create as JS
Parameters: {"utf8"=>"✓", "authenticity_token"=>"nUhePXUdztraIcRVmQ6ewMjzLBPLbCJKjvGUExoQu7XH+zTJYj9J/+wopP7kAI1ycAa5t0bG7fEuApgAQqcDDw==", "followed_id"=>"4", "commit"=>"Follow"}
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 1]]
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 4]]
(0.1ms) begin transaction
SQL (0.5ms) INSERT INTO "relationships" ("followed_id", "follower_id", "created_at", "updated_at") VALUES (?, ?, ?, ?) [["followed_id", 4], ["follower_id", 1], ["created_at", "2015-11-21 15:42:41.359403"], ["updated_at", "2015-11-21 15:42:41.359403"]]
(3.4ms) commit transaction
Rendered users/_unfollow.html.erb (7.6ms)
Rendered relationships/create.js.erb (10.4ms)
Completed 500 Internal Server Error in 35ms (ActiveRecord: 4.6ms)
NoMethodError (undefined method `id' for nil:NilClass):
app/views/users/_unfollow.html.erb:1:in `_app_views_users__unfollow_html_erb__4478734189885612533_2206022220'
app/views/relationships/create.js.erb:1:in `_app_views_relationships_create_js_erb___3841425439351308004_2234925000'
app/controllers/relationships_controller.rb:8:in `create'
Started DELETE "/relationships/106" for ::1 at 2015-11-21 10:44:16 -0500
Processing by RelationshipsController#destroy as JS
Parameters: {"utf8"=>"✓", "authenticity_token"=>"MQQWiFHmikzre6tgsaVNf25z1r4Ps4yMhiX6BVAHvWFrt3x8RsQNad1yy8vMq17N1oZDGoIZQzcm1vYWCLAF2w==", "commit"=>"Unfollow", "id"=>"106"}
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 1]]
Relationship Load (0.2ms) SELECT "relationships".* FROM "relationships" WHERE "relationships"."id" = ? LIMIT 1 [["id", 106]]
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 4]]
Relationship Load (0.6ms) SELECT "relationships".* FROM "relationships" WHERE "relationships"."follower_id" = ? AND "relationships"."followed_id" = ? LIMIT 1 [["follower_id", 1], ["followed_id", 4]]
(0.4ms) begin transaction
SQL (1.3ms) DELETE FROM "relationships" WHERE "relationships"."id" = ? [["id", 106]]
(571.2ms) commit transaction
Rendered users/_follow.html.erb (7.3ms)
Rendered relationships/destroy.js.erb (10.0ms)
Completed 500 Internal Server Error in 608ms (ActiveRecord: 574.0ms)
NoMethodError (undefined method `id' for nil:NilClass):
app/views/users/_follow.html.erb:2:in `block in _app_views_users__follow_html_erb__4224173111585839618_2218160400'
app/views/users/_follow.html.erb:1:in `_app_views_users__follow_html_erb__4224173111585839618_2218160400'
app/views/relationships/destroy.js.erb:1:in `_app_views_relationships_destroy_js_erb___1536758446230344516_2256927580'
app/controllers/relationships_controller.rb:18:in `destroy'
第一次单击unfollow按钮时会产生500错误,然后在随后按下404错误。(见图)
单击unfollow按钮后,服务器控制台如下所示:
Started POST "/relationships" for ::1 at 2015-11-21 10:42:41 -0500
Processing by RelationshipsController#create as JS
Parameters: {"utf8"=>"✓", "authenticity_token"=>"nUhePXUdztraIcRVmQ6ewMjzLBPLbCJKjvGUExoQu7XH+zTJYj9J/+wopP7kAI1ycAa5t0bG7fEuApgAQqcDDw==", "followed_id"=>"4", "commit"=>"Follow"}
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 1]]
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 4]]
(0.1ms) begin transaction
SQL (0.5ms) INSERT INTO "relationships" ("followed_id", "follower_id", "created_at", "updated_at") VALUES (?, ?, ?, ?) [["followed_id", 4], ["follower_id", 1], ["created_at", "2015-11-21 15:42:41.359403"], ["updated_at", "2015-11-21 15:42:41.359403"]]
(3.4ms) commit transaction
Rendered users/_unfollow.html.erb (7.6ms)
Rendered relationships/create.js.erb (10.4ms)
Completed 500 Internal Server Error in 35ms (ActiveRecord: 4.6ms)
NoMethodError (undefined method `id' for nil:NilClass):
app/views/users/_unfollow.html.erb:1:in `_app_views_users__unfollow_html_erb__4478734189885612533_2206022220'
app/views/relationships/create.js.erb:1:in `_app_views_relationships_create_js_erb___3841425439351308004_2234925000'
app/controllers/relationships_controller.rb:8:in `create'
Started DELETE "/relationships/106" for ::1 at 2015-11-21 10:44:16 -0500
Processing by RelationshipsController#destroy as JS
Parameters: {"utf8"=>"✓", "authenticity_token"=>"MQQWiFHmikzre6tgsaVNf25z1r4Ps4yMhiX6BVAHvWFrt3x8RsQNad1yy8vMq17N1oZDGoIZQzcm1vYWCLAF2w==", "commit"=>"Unfollow", "id"=>"106"}
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 1]]
Relationship Load (0.2ms) SELECT "relationships".* FROM "relationships" WHERE "relationships"."id" = ? LIMIT 1 [["id", 106]]
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 4]]
Relationship Load (0.6ms) SELECT "relationships".* FROM "relationships" WHERE "relationships"."follower_id" = ? AND "relationships"."followed_id" = ? LIMIT 1 [["follower_id", 1], ["followed_id", 4]]
(0.4ms) begin transaction
SQL (1.3ms) DELETE FROM "relationships" WHERE "relationships"."id" = ? [["id", 106]]
(571.2ms) commit transaction
Rendered users/_follow.html.erb (7.3ms)
Rendered relationships/destroy.js.erb (10.0ms)
Completed 500 Internal Server Error in 608ms (ActiveRecord: 574.0ms)
NoMethodError (undefined method `id' for nil:NilClass):
app/views/users/_follow.html.erb:2:in `block in _app_views_users__follow_html_erb__4224173111585839618_2218160400'
app/views/users/_follow.html.erb:1:in `_app_views_users__follow_html_erb__4224173111585839618_2218160400'
app/views/relationships/destroy.js.erb:1:in `_app_views_relationships_destroy_js_erb___1536758446230344516_2256927580'
app/controllers/relationships_controller.rb:18:in `destroy'
在Chrome developer tools中,显示触发错误的代码如下:
xhr.send( ( options.hasContent && options.data ) || null );
我将把问题分为以下两部分。。。添加启用ajax的按钮之前的工作,以及开始产生错误的代码添加
正在工作:标准按钮 这就是切换到Ajax之前的工作: 关系\u controller.rb
class RelationshipsController < ApplicationController
before_action :logged_in_user
def create
user = User.find(params[:followed_id])
current_user.follow(user)
redirect_to user
end
def destroy
user = Relationship.find(params[:id]).followed
current_user.unfollow(user)
redirect_to user
end
end
<%= form_for(current_user.active_relationships.build) do |f| %>
<div><%= hidden_field_tag :followed_id, @user.id %></div>
<%= f.submit "Follow", class: "btn btn-primary" %>
<% end %>
<%= form_for(current_user.active_relationships.find_by(followed_id: @user.id),
html: { method: :delete }) do |f| %>
<%= f.submit "Unfollow", class: "btn" %>
<% end %>
require 'test_helper'
class FollowingTest < ActionDispatch::IntegrationTest
def setup
@user = users(:michael)
@other = users(:archer)
log_in_as(@user)
end
test "following page" do
get following_user_path(@user)
assert_not @user.following.empty?
assert_match @user.following.count.to_s, response.body
@user.following.each do |user|
assert_select "a[href=?]", user_path(user)
end
end
test "followers page" do
get followers_user_path(@user)
assert_not @user.followers.empty?
assert_match @user.followers.count.to_s, response.body
@user.followers.each do |user|
assert_select "a[href=?]", user_path(user)
end
end
test "should follow a user the standard way" do
assert_difference '@user.following.count', 1 do
post relationships_path, followed_id: @other.id
end
end
test "should follow a user with Ajax" do
assert_difference '@user.following.count', 1 do
xhr :post, relationships_path, followed_id: @other.id
end
end
test "should unfollow a user the standard way" do
@user.follow(@other)
relationship = @user.active_relationships.find_by(followed_id: @other.id)
assert_difference '@user.following.count', -1 do
delete relationship_path(relationship)
end
end
test "should unfollow a user with Ajax" do
@user.follow(@other)
relationship = @user.active_relationships.find_by(followed_id: @other.id)
assert_difference '@user.following.count', -1 do
xhr :delete, relationship_path(relationship)
end
end
end
<%= form_for(current_user.active_relationships.build, remote: true) do |f| %>
<div><%= hidden_field_tag :followed_id, @user.id %></div>
<%= f.submit "Follow", class: "btn btn-primary" %>
<% end %>
<%= form_for(current_user.active_relationships.find_by(followed_id: @user.id),
html: { method: :delete },
remote: true) do |f| %>
<%= f.submit "Unfollow", class: "btn" %>
<% end %>
class RelationshipsController < ApplicationController
before_action :logged_in_user
def create
@user = User.find(params[:followed_id])
current_user.follow(@user)
respond_to do |format|
format.html { redirect_to @user }
format.js
end
end
def destroy
@user = Relationship.find(params[:id]).followed
current_user.unfollow(@user)
respond_to do |format|
format.html { redirect_to @user }
format.js
end
end
end
$("#follow_form").html("<%= escape_javascript(render('users/unfollow')) %>");
$("#followers").html('<%= @user.followers.count %>');
$("#follow_form").html("<%= escape_javascript(render('users/follow')) %>");
$("#followers").html('<%= @user.followers.count %>');
官方教程的github在这里:我有一个确切的问题。虽然您的代码片段反映了这一变化,但对我来说,问题是Hartl没有突出显示他在
relationships\u controller.rb
中所做的一项关键更改(他确实在本文中谈到了这一点,我在本教程的这一点上略过)
变化是user
从常规变量变为实例变量。因此:
user = User.find(params[:followed_id])
变成
@user = User.find(params[:followed_id])
添加了该更改后,nil:NilClass的ActionView::Template::Error:undefined方法“id”错误得到了解决