[英]Rails ajax, not able to append new record in table
我试图在我的rails应用程序中使用ajax。 显示_form
创建new student
记录时,我的ajax运行正常。 但是一旦创建了新学生,我想隐藏_form
并显示list of students
并在表格底部添加新学生记录。
目前,我的代码正在创建新的学生记录,隐藏新的_form
并显示学生列表。 但是由于某种原因,新学生记录没有被添加到表格的底部。 刷新页面后,我可以看到表格底部显示的新生记录。 但是我想在不刷新页面的情况下实现此行为。
以下是我的代码:
students_controller.rb
def index
@students = Student.all
end
def new
@student = Student.new
end
def create
@student = Student.new(student_params)
@student.save
end
private
def student_params
params.require(:student).permit(:name)
end
index.html.erb文件
<div id="student-list">
<h1>Listing Students</h1>
<table>
<thead>
<tr>
<th>Name</th>
<th colspan="3"></th>
</tr>
</thead>
<tbody>
<div id='all-students'>
<%= render @students %>
</div>
</tbody>
</table>
<br>
<%= link_to 'New Student', new_student_path, remote: true %>
</div>
<div id='new-form'></div>
_student.html.erb部分
<tr>
<td><%= student.name %></td>
<td><%= link_to 'Show', student %></td>
<td><%= link_to 'Edit', edit_student_path(student) %></td>
<td><%= link_to 'Destroy', student, method: :delete, data: { confirm: 'Ary you sure?' } %></td>
</tr>
new.js.erb文件(此文件工作正常)
$("#student-list").hide();
$("#new-form").html("<%= j render 'form' %>");
_form.html.erb部分
<%= form_for(@student, remote: true) do |f| %>
<div class="field">
<%= f.label :name %><br>
<%= f.text_field :name %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
<%= link_to '<< back', students_path, remote: true %>
create.js.erb文件(此文件不起作用)
$("#all_students").append("<%= j render @student %>");
$("#new-form").hide();
$("#student-list").show();
我正在使用Rails 4.2.5和ruby 2.3.0
这是rails server
输出
Started POST "/students" for ::1 at 2016-03-24 00:44:23 +1100
Processing by StudentsController#create as JS
Parameters: {"utf8"=>"✓", "student"=>{"name"=>"dd"}, "commit"=>"Create Student"}
(0.1ms) begin transaction
SQL (0.3ms) INSERT INTO "students" ("name", "created_at", "updated_at") VALUES (?, ?, ?) [["name", "dd"], ["created_at", "2016-03-23 13:44:23.465302"], ["updated_at", "2016-03-23 13:44:23.465302"]]
(0.7ms) commit transaction
Rendered students/_student.html.erb (0.4ms)
Rendered students/create.js.erb (8.4ms)
Completed 200 OK in 21ms (Views: 18.6ms | ActiveRecord: 1.0ms)
这是浏览器的输出(Chrome->网络-> XHR)
$("#all_students").append("<tr>\n <td>dd<\/td>\n <td><a href=\"/students/43\">Show<\/a><\/td>\n <td><a href=\"/students/43/edit\">Edit<\/a><\/td>\n <td><a data-confirm=\"Ary you sure?\" rel=\"nofollow\" data-method=\"delete\" href=\"/students/43\">Destroy<\/a><\/td>\n<\/tr>\n");
$("#new-form").hide();
$("#student-list").show();
在文件create.js.erb中,将#all_students
替换为#all-students
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.