问题
I am implementing triply nested form where you can see I am also showing the triply nested Task model's content and also rendering a form to add new Task. The task list is displayed correctly- which means the fet has a valid Feature model, But dont know why it is failing when rendering the new task form unexpectedly!! where it shows->
ActionController::UrlGenerationError in Projects#show
No route matches {:action=>"index", :controller=>"tasks", :feature_id=>nil}, missing required keys: [:feature_id]
<% @project.features.each do |fet| %>
<div class="card p-2">
<%= "#{fet.name} #{fet.id}" %>
<!-- new Taskform loading is showing problem -->
<%= render :partial => "taskform", :locals => {:feature => fet} %>
<!-- this one is displaying task list properly -->
<div class="card-body">
Tasks:
<% fet.tasks.each do |t| %>
<%= "#{t.name}" %>
<%= "#{t.completed}" %>
<%= "#{t.user_id}" %>
<% end %>
</div>
</div>
<% end %>
my _taskform.html.erb
header looks like->
<%= form_for [feature, feature.tasks.build], method: :post, class: "form-group row" do |builder| %>
(rest part is irrelvent I guess, so I did't include)
Now the routes.rb is,
resources :projects do
resources :features, shallow: true do
resources :tasks
end
end
Please help me find out the possible reason for ambiguity of behaviour when showing and creating new .
N.B: I just noticed that in the eror message-it says No route matches {:action=>"index",
which is unexpected, obviously I am trying to refer to the new action to create new task under a Feature( form_for [feature, feature.tasks.build]
)
回答1:
form_for [feature, feature.tasks.build]
complains about the missing feature_id
value because your route definition is nested inside a project and you are not passign the project.
From your routes definition, your route should be something projects/:project_id/features/:feature_id/tasks
. You need to provide both ids.
form_for [feature, feature.tasks.build]
is using feature.id
as :project_id
and the new taks object's id (nil because it's not saved) as the value for :feature_id
for your route.
To fix that, split the nesting in two:
resources :projects do
resources :features
end
resources :features do
resources :tasks
end
(more than one level of nesting is discouraged by rails guidelines.
If you still want to use the 3 level nesting, then pass the project to the form_for helper:
form_for [@project, feature, feature.tasks.build] ...
来源:https://stackoverflow.com/questions/57527439/triply-nested-models-form-in-rails-showing-error