ruby-on-rails - 关联模型的表单对象中的 NoMethodError
问题描述
我正在构建一个项目管理应用程序。我的系统就像-一个项目有很多功能,一个功能有很多任务。并且 routes.rb 被定义为
resources :projects do
resources :features do
resources :tasks
end
end
第一级,即项目到功能对于新功能表单工作正常,但是当我尝试将新任务表单实现为 ->
<%= form_for([@feature, @feature.tasks.build], class: "form-group row") do |form| %>
<%= form.label :name %>
<%= form.text_field :name, required:true, class: "form-control" %>
<%= form.submit class: "btn btn-primary m-2" %>
<% end %>
现在它显示错误为
这是我的模型->
class Task < ApplicationRecord
belongs_to :feature
end
class Feature < ApplicationRecord
belongs_to :project
has_many :tasks
end
任务的控制器看起来像->
class TasksController < ApplicationController
before_action :set_feature
def new
@task = @feature.tasks.new
end
def create
@task = @feature.tasks.new(task_params)
if @task.save
redirect_to project_features_path
else
render :new
end
end
def edit
end
def update
if @task.update(task_params)
redirect_to project_feature_tasks_path
else
render :edit
end
end
def complete
@task.update(completed: true)
redirect_to project_feature_tasks_path
end
def destroy
@feature.task.destroy
redirect_to project_feature_tasks_path
end
private
def set_feature
@feature = Feature.find(params[:feature_id])
end
def task_params
params.require(:task).permit(:name,:completed, :project_id,:feature_id)
end
end
非常感谢任何帮助 - 我现在被这个错误困扰了好几天。
解决方案
如果您尝试跑步$ rails routes
,您可以看到为什么您当前的路线让您失望。
Prefix Verb URI Pattern Controller#Action
project_feature_tasks GET /projects/:project_id/features/:feature_id/tasks(.:format) tasks#index
POST /projects/:project_id/features/:feature_id/tasks(.:format) tasks#create
new_project_feature_task GET /projects/:project_id/features/:feature_id/tasks/new(.:format) tasks#new
edit_project_feature_task GET /projects/:project_id/features/:feature_id/tasks/:id/edit(.:format) tasks#edit
project_feature_task GET /projects/:project_id/features/:feature_id/tasks/:id(.:format) tasks#show
PATCH /projects/:project_id/features/:feature_id/tasks/:id(.:format) tasks#update
PUT /projects/:project_id/features/:feature_id/tasks/:id(.:format) tasks#update
DELETE /projects/:project_id/features/:feature_id/tasks/:id(.:format)
您必须致电:
form_for([@project, @feature, @feature.tasks.build], ...) do |form|
一个更好的主意是取消嵌套路由。您可以使用以下shallow
选项来执行此操作:
resources :projects do
resources :features, shallow: true do
resources :tasks
end
end
或者,如果您出于某种原因想要保留嵌套功能的成员路由(显示、编辑、更新、销毁),则可以这样做:
resources :projects do
resources :features
end
resources :features, only: [] do
resources :tasks
end
推荐阅读
- r - 如何在 Excel 或 R 中将一列的数据拆分为多个相等的 n 列?
- python - 将 paho.mqtt.python 连接到 mosquitto 代理时出现套接字错误
- python - {Class}.query.all() 请求未从表中检索所有数据的 Flask-SQLAlchemy 问题
- debugging - 如何从您的 Web 应用程序连接本地托管的 Azure BOT
- python - 通过 Selenium 在 facebook 上解码类名
- c - Separating JSON array elements as a string in C
- android - 如何将 NavArgs 映射到 NavArgument?
- node.js - 节点红色内存不足问题
- r - 根据其他列中的二进制值创建一个新的条件列?(右)
- javascript - 正则表达式 - 如何匹配同时匹配和不匹配模式的所有字符组?