Triply nested model's form in rails showing error

懵懂的女人 提交于 2019-12-13 17:19:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!