我有2个模型 - 项目和待办事项,项目包含许多待办事项。我正在尝试编写一个表单,该表单会在托盘中选择的特定项目中添加待办事项。
不幸的是我收到错误
当我重定向到/ todos时,来自todos_controller的无法找到带有' id' =
的项目
@project = Project.find(params [:project_id])
/projects/index.html.erb
<h1> Задачи </h1>
<% @projects.each do |project_name|%>
<h3><%= project_name.title %></h3>
<ul>
<% project_name.todos.each do |project_todo| %>
<li>
<p><%= project_todo.text %></p>
</li>
<% end %>
</ul>
<% end %>
<h1> Новая задача </h1>
<%= form_with scope: :todo, url: todos_path, local: true do |form| %>
<p>
<% form.label :text %><br>
<%= form.text_field :title, placeholder: "Название задачи" %>
</p>
<%= form.select( :project_id, options_from_collection_for_select(Project.all, :id, :title)) %>
<p>
<a href="/projects">ОТМЕНА</a>
<%= link_to form.submit %>
</p>
<% end %>
projects_controller.rb
class ProjectsController < ApplicationController
def index
@projects = Project.all
respond_to do |format|
format.html
format.json {render json: @projects}
end
end
todos_controller.rb
class TodosController < ApplicationController
def index
@todos = Todo.all
respond_to do |format|
format.html
format.json {render json: @todos}
end
end
def update
end
def create
@project = Project.find(params[:project_id])
@todo = @project.todo.create(todo_params)
redirect_to projects_path
end
end
的routes.rb
Rails.application.routes.draw do
resources :projects, :todos
root 'projects#index'
end
我也无法将提交按钮显示为文本链接。
答案 0 :(得分:0)
您的控制器需要project_id
参数,该参数可能不通过!当您触发todos#create
方法
答案 1 :(得分:0)
将create
操作修改为
def create
@project = Project.find(params[:todo][project_id])
@todo = @project.todo.create(todo_params)
redirect_to projects_path
end
如果不起作用,那么检查服务器日志中的params散列并检查project_id是否存在于params中。
上面会有效,但我认为如果你将创建动作修改为
,则不需要找到项目 def create
@todo = Todo.create(todo_params)
redirect_to projects_path
end
还将方法定义为
def todo_params
params.require(:todo).permit(:project_id, :title)
end
答案 2 :(得分:0)
params [:project_id]是nil,因为你提交todo的表单,所以你需要访问project_id as
创建操作中的Project.find(params[:todo][project_id])
。
因此,请按以下步骤替换您的创建操
def创建
@project = Project.find(params [:todo] [project_id])
@todo = @ project.todo.create(todo_params)
redirect_to projects_path
结束
别忘了在todo_params方法中包含project_id。