我目前正在做一个简单的应用程序,我正在尝试在创建新任务时实现ajax。我试图渲染部分将包含新任务的信息,然后将其附加到已存在的表,但我不断收到以下错误:
POST http://localhost:3000/projects/4/tasks 500 (Internal Server Error)
这是我的任务创建表单
# app/view/tasks/_create_task.html.erb
<div class="row">
<div class="col-md-5">
<%=form_for [@project, @task], remote: true do |f| %>
<div class="form-group">
<%=f.label :task_name %>
<%=f.text_field :task_name, class: "form-control"%>
</div>
<div class="form-group">
<%=f.label :deadline %>
<%=date_select :task, :deadline, class: "form-control" %>
</div>
<%=f.submit "Create task", class: 'btn btn-info' %>
<%end%>
</div>
</div>
这是我的任务创建操作的控制器代码
#app/controllers/tasks_controller.rb
before_action :set_project
def create
@task = @project.tasks.build(set_params).save
respond_to do |format|
format.html do
if @task.valid?
flash[:notice] = "Your task has been successfully saved"
redirect_to project_path(@project)
else
render 'projects/show'
end
end
format.js
end
end
private
def set_params
params.require(:task).permit!
end
def set_project
@project = Project.find(params[:project_id])
end
和相应的create.js.erb模板
#app/view/tasks/create.js.erb
$('#task-table').append("<%= j render 'task', task: @task, project: @project%>");
最后是我试图渲染的部分:
#app/views/tasks/_task
<% if task.erased %>
<% row_class = 'hidden'%>
<% end %>
<% if task.erased == nil && task.checked %>
<% row_class = 'row-disabled success' %>
<% icon_class = 'glyphicon glyphicon-ok check-icon' %>
<%elsif task.erased == nil && task.checked == nil %>
<% row_class = '' %>
<% icon_class = 'glyphicon glyphicon-unchecked check-icon ' %>
<% end %>
<tr class = "<%= row_class %>" id = 'task-row' >
<td>
<%= link_to project_check_task_path(project, task, checked: true), method: 'patch' do %>
<span class= "<%=icon_class %>"></span>
<% end %>
</td>
<td><%= task.task_name %></td>
<td><%= task.created_at.strftime("%b %d, %Y")%></td>
<td><%= task.deadline.strftime("%b %d, %Y")%></td>
<td>
<%= link_to project_erase_task_path(project, task, erase: true), method: 'patch' do %>
<span class = "glyphicon glyphicon-trash"></span>
<% end %>
</td>
</tr>
注意:我没有渲染部分内容,而是尝试附加任何动态内容,例如@ task.title等,并且都抛出同样的错误。
感谢您的帮助。
答案 0 :(得分:1)
您遇到的问题可能来自以下几行:
@task = @project.tasks.build(set_params).save
因为@project.tasks.build(set_params).save
会返回true
或false
,而您将其视为任务对象。
应该是:
@task = @project.tasks.build(set_params)
@task.save
或
@task = @project.tasks.create(set_params)