我有一个小问题,希望得到一些帮助。
我有一个块和一个位于同一页面上的表单,当该表单位于该块下方时,它可以正常工作:
<% @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,但没有帮助。
这是我的任务控制器中的create动作:
def create
@project = Project.find(params[:project_id])
@task = @project.tasks.create(task_params)
redirect_to @project
end
有谁知道为什么我不能将表格放在块上方?
修改后的答案。我模拟了这种情况,以检查正在发生的事情,下面是一个有效的示例,我相信它可以实现您想要的目标。
我认为您遇到的问题更多来自控制器设置。请参阅下面的index操作和create操作中的注释,以了解如何构建任务。
路线:
# 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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句