Using form_for with Nested Resources

前端 未结 1 811
面向向阳花
面向向阳花 2021-01-06 21:44

I am building a To Do application in an attempt to get fluent with Rails. There are four levels of hierarchy in my app.

  1. User
  2. Goals (multiple goals p
相关标签:
1条回答
  • 2021-01-06 22:33

    It is typically bad practice to nest routes beyond two levels deep. I would change your routes to:

      resources :goal do
        resources :task 
      end
    

    and

      resources :task do
          resources :subtask
      end
    

    Now if you run "bundle exec rake routes" in the command line you will see all of the nested routes and their corresponding helpers. Your current issue lies with the form_for method. You need to add the resource its nested with which in this case should be:

    <%= form_for [@goal,@task] do |f| %>
        blah blah
    <% end %>
    

    Lastly, @goal is also still undefined so you'll need to define it in your 'new' action in the tasks controller. This is normally done by passing the id of the goal your task will be associated with via the params hash and the "link_to" used to get to the 'new' form. Then in the new action in your tasks controller:

    @goal = Goal.find(params[:goal_id]) #The parameter can be named anything
    @task = Task.new
    

    Then in your 'create' action you should have the association made:

    @task = Goal.tasks.new(task_params)
    if @task.save
       flash[:success] = "Woot" 
       redirect_to somewhere_awesome_path
    else
      whatever
    end
    
    0 讨论(0)
提交回复
热议问题