我有一个小问题,我希望得到一些帮助。
我有一个块和一个位于同一页面上的表单,当表单位于块下方时工作正常:
<% @project.tasks.each do |task| %>
<%= link_to task.title, project_task_path(@project, task) %>
<% end %>
<%= form_for([@project, @project.tasks.build]) do |f| %>
<%= f.text_field :title, placeholder: 'Add a Task' %>
<%= f.submit %>
<% end %>
但是当我将表单放在块上方时,我收到一条错误,指出我的任务ID丢失了:
No route matches {:action=>"show", :controller=>"tasks", :id=>nil, :project_id=>"14"} missing required keys: [:id]
我最好的猜测是我的表单中的构建方法是罪魁祸首。我尝试用.new替换.build,但它没有帮助。
以下是我的任务控制器的创建操作:
def create
@project = Project.find(params[:project_id])
@task = @project.tasks.create(task_params)
redirect_to @project
end
有谁知道为什么我不能把表格放在街区上面?
答案 0 :(得分:0)
修改后的答案。我嘲笑这个场景来检查发生了什么,下面是一个我认为可以实现你想要的工作实例。
我认为您遇到的问题更多来自您的控制器设置。请参阅索引操作中的注释和下面的创建操作,以了解我是如何构建任务的。
路线:
# config/routes.rb
Rails.application.routes.draw do
resources :projects do
resources :tasks
end
root 'tasks#index'
end
任务控制器:
# app/controllers/tasks_controller.rb
# un-modified actions left out.
class TasksController < ApplicationController
before_action :set_task, only: [:show, :edit, :update, :destroy]
# GET /tasks
# GET /tasks.json
def index
# Create the parent project from the url id
@project = Project.find(params[:project_id])
# Create a new task from the params from the form
@task = @project.tasks.new
# Get all tasks for your list
@tasks = @project.tasks.all
end
# POST /tasks
# POST /tasks.json
def create
# Create the parent project from the url id
@project = Project.find(params[:project_id])
# Create a new task from the params from the form
@task = @project.tasks.new(task_params)
# try and save the task.
respond_to do |format|
if @task.save
format.html { redirect_to @project, notice: 'Task was successfully created.' }
else
format.html { render :index }
end
end
end
end
任务索引视图:
#app/views/tasks/index.html.erb
p id="notice"><%= notice %></p>
<%= form_for([@project, @task]) do |f| %>
<% if @task.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@task.errors.count, "error") %> prohibited this task from being saved:</h2>
<ul>
<% @task.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :name %><br>
<%= f.text_field :name %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
<h1>Listing Tasks</h1>
<table>
<thead>
<tr>
<th>Name</th>
<th colspan="3"></th>
</tr>
</thead>
<tbody>
<% @tasks.each do |task| %>
<tr>
<td><%= task.name %></td>
</tr>
<% end %>
</tbody>
</table>
<br>