我正在努力完成在Rails http://guides.rubyonrails.org/working_with_javascript_in_rails.html中使用JavaScript的第5部分。
我的问题是,在刷新整个页面之前,新用户不会显示在显示页面中。我认为我已正确复制了所有代码,但无法查看错误。
users_controller
class UsersController < ApplicationController
before_action :set_user, only: [:show, :edit, :update, :destroy]
def index
@users = User.all
@user = User.new
end
...
def create
@user = User.new(user_params)
respond_to do |format|
if @user.save
format.html { redirect_to @user, notice: 'User was successfully created.' }
format.js
format.json { render json: @user, status: :created, location: @user }
else
format.html { render :new }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
用户/ index.html.erb
<b>Users</b>
<ul id="users">
<%= render @users %>
</ul>
<br>
<%= form_with(model: @user) do |f| %>
<%= f.label :name %><br>
<%= f.text_field :name %>
<%= f.submit %>
<% end %>
用户/ create.js.erb
$("<%= escape_javascript(render @user) %>").appendTo("#users");
日志
started POST "/users" for 127.0.0.1 at 2018-03-30 17:23:36 +0100
Processing by UsersController#create as JS
Parameters: {"utf8"=>"✓", "authenticity_token"=>"xMBe+h9zi5rWE8JXltYw1fGwQUP8AL2iWaaaGVqwbPvYavJgv7eQ0J5hwRL9xkb2S0pnose3X6oo+YXywvlcaQ==", "user"=>{"name"=>"Dave"}, "commit"=>"Create User"}
(0.2ms) BEGIN
SQL (0.7ms) INSERT INTO "users" ("name", "created_at", "updated_at") VALUES ($1, $2, $3) RETURNING "id" [["name", "Dave"], ["created_at", "2018-03-30 16:23:36.474360"], ["updated_at", "2018-03-30 16:23:36.474360"]]
(6.3ms) COMMIT
Rendering users/create.js.erb
Rendered users/_user.html.erb (0.3ms)
Rendered users/create.js.erb (3.7ms)
Completed 200 OK in 28ms (Views: 13.6ms | ActiveRecord: 7.3ms)
Started GET "/users" for 127.0.0.1 at 2018-03-30 17:23:38 +0100
Processing by UsersController#index as HTML
Rendering users/index.html.erb within layouts/application
User Load (0.3ms) SELECT "users".* FROM "users"
Rendered collection of users/_user.html.erb [3 times] (0.4ms)
Rendered users/index.html.erb within layouts/application (5.4ms)
Completed 200 OK in 54ms (Views: 49.7ms | ActiveRecord: 0.3ms)