![](/img/trans.png)
[英]Tableless Model - NoMethodError on creating object from form params
[英]NoMethodError in Associated model's form object
我正在構建一個項目管理應用程序。 我的系統就像-一個項目有很多功能,一個功能有很多任務。 並且route.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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.