我正在构建一个To Do应用程序,以尝试使Rails变得流畅.我的应用程序有四个层次结构.
I am building a To Do application in an attempt to get fluent with Rails. There are four levels of hierarchy in my app.
对于使用嵌套资源的每一个,我都有一个有效的前端表单.我的routes.rb有这样的内容
I have a working front end form for each of these that utilizes nested resources. My routes.rb has something like this
resources :goal do resources :task do resources :subtask end end我现在想做的是在用户控制器的视图之一中拥有所有这些表格.
What I would like to do now is that have all these forms right in one of the views of the user controller.
这是我尝试创建的表单:
This the form that I have attempted to create :
<%= form_for @task, url: {controller: 'task', action: 'create'} do |f| %> <%= f.label :description %> <%= f.text_field :description %> <%= f.submit "Add Goal", class: "btn" %> <% end %>但是我最终收到此错误
No route matches {:action=>"create", :controller=>"task", :id=>"1"}:id => 1对应于我所在的用户页面( localhost:3000/user /1 )
The :id=>1 corresponds to the user page I am on (localhost:3000/user/1)
我了解到的是,我在任何地方都没有提供此步骤打算使用的goal_id.不知道如何实现这一点.
What I understand is that there is that nowhere have I provided the goal_id for which this step is intended. No idea how to implement this.
我注意到的另一件事是,对rake routes的响应显示了很多URI路径,但对于POST方法却没有任何显示.它不允许我使用form_for中url:中从那里开始的路径,因为它与POST方法不匹配.
Another thing that I have noticed is that a response to rake routes shows a lot of URI paths but nothing for POST method. It does not allow me to use a path from there in the url: in form_for because it does not match the POST method.
所以我的问题是:
推荐答案
将路由嵌套超过两层通常是不好的做法.我会将您的路线更改为:
It is typically bad practice to nest routes beyond two levels deep. I would change your routes to:
resources :goal do resources :task end和
resources :task do resources :subtask end现在,如果在命令行中运行"bundle exec rake路由",您将看到所有嵌套的路由及其对应的帮助程序.您当前的问题在于form_for方法.您需要添加其嵌套的资源,在这种情况下,资源应为:
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 %>最后,@ goal仍未定义,因此您需要在任务控制器的新"操作中对其进行定义.通常,这是通过传递您的任务的目标ID(通过params哈希值)和用于获取新"表单的"link_to"来完成的.然后在您的任务控制器中执行新操作:
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更多推荐
在嵌套资源中使用form
发布评论