为更多信息而重组
我会相当短暂。作为一个新手,这是我在开发rails应用程序时遇到的错误:
param is missing or the value is empty: task
错误突出显示:
def task_params
params.require(:task).permit(:name, :description, :deadline, :status, :pdf, :done)
end
当我点击“标记为已完成”按钮时,会发生我正在创建。
以下是代码:
应用程序/视图/任务/ index.html.erb:
<p id="notice"><%= notice %></p>
<h1>Tasks</h1>
<table>
<thead>
<tr>
<th>Name</th>
<th>Description</th>
<th>Time</th>
<th>Ready?</th>
<th colspan="10"></th>
</tr>
</thead>
<tbody>
<% @tasks.each do |task| %>
<tr>
<td><%= task.name %></td>
<td><%= task.description %></td>
.
.
.
<td><%= (link_to 'Mark done', task_path(task, done: true), method: :PUT) %></td>
</tr>
<% end %>
</tbody>
</table>
<br>
应用程序/控制器/ tasks_controller.rb:
class TasksController < ApplicationController
before_action :set_task, only: [:show, :edit, :update, :destroy]
# GET /tasks
# GET /tasks.json
def index
@tasks = Task.all
end
# GET /tasks/1
# GET /tasks/1.json
def show
end
# GET /tasks/new
def new
@task = Task.new
end
# GET /tasks/1/edit
def edit
end
# POST /tasks
# POST /tasks.json
def create
@task = Task.new(task_params)
respond_to do |format|
if @task.save
format.html { redirect_to @task, notice: 'Task was successfully created.' }
format.json { render :show, status: :created, location: @task }
else
format.html { render :new }
format.json { render json: @task.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /tasks/1
# PATCH/PUT /tasks/1.json
def update
respond_to do |format|
if @task.update(task_params)
format.html { redirect_to @task, notice: 'Task was successfully updated.' }
format.json { render :show, status: :ok, location: @task }
else
format.html { render :edit }
format.json { render json: @task.errors, status: :unprocessable_entity }
end
end
end
# DELETE /tasks/1
# DELETE /tasks/1.json
def destroy
@task.destroy
respond_to do |format|
format.html { redirect_to tasks_url, notice: 'Task was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_task
@task = Task.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def task_params
params.require(:task).permit(:name, :description, :deadline, :status, :pdf, :done)
end
end
感谢您的帮助!
答案 0 :(得分:1)
因为您已按照命令
中的说法在控制器中完成此操作before_action :set_task
def set_task
@task = Task.find(params[:id)
end
你应该能够做到:
<td><%= 'Mark as done', tasks_setdone_path(task), method: :post %></td>
而不是<td><%= 'Mark as done', tasks_setdone_path(task), method: :post %></td>
&#39; @&#39;表示可从控制器和模板访问的实例变量。
另一件事是你的动作控制器需要响应(html或json)。
现在你给出了回答,这是正确的方法。
task_path(@task, done: true), method: :PUT
POST用于创建,其中PUT用于更新对象。