首页 > 解决方案 > ruby on rails 中的简单形式 - 嵌套

问题描述

我只是对简单的形式和嵌套感到好奇。我读过文件,但还是不太明白。

我使用设备创建了一个网站,用户可以在其中发布推文并编辑推文。我的印象是 [@user, @tweet] 需要出现在新表单和编辑表单的 simple_form_for 中。但是我发现 [@user, @tweet] 需要在新表单上,只有 [@tweet] 需要在编辑表单上。它是否正确?我有点不清楚这是如何工作的。是不是因为需要为用户分配一条新推文,因此使用了@user 和@tweet,而要编辑一条推文,则不需要@user,因为不需要它?道歉,如果这没有意义。

标签: ruby-on-railsrubynested

解决方案


我有点不清楚这是如何工作的。是不是因为需要为用户分配一条新推文,因此使用了@user 和@tweet,而要编辑一条推文,则不需要@user,因为不需要它?

简短的回答是“是”。更长的答案是...

我不知道,但我猜这些路线看起来像:

resources :user do 
  resources :tweets, shallow: true 
end

这会给你类似的东西:

    user_tweets GET    /users/:user_id/tweets(.:format)          tweets#index
                POST   /users/:user_id/tweets(.:format)          tweets#create
 new_user_tweet GET    /users/:user_id/tweets/new(.:format)      tweets#new
     edit_tweet GET    /tweets/:id/edit(.:format)                tweets#edit
          tweet GET    /tweets/:id(.:format)                     tweets#show
                PATCH  /tweets/:id(.:format)                     tweets#update
                PUT    /tweets/:id(.:format)                     tweets#update
                DELETE /tweets/:id(.:format)                     tweets#destroy
          users GET    /users(.:format)                          users#index
                POST   /users(.:format)                          users#create
       new_user GET    /users/new(.:format)                      users#new
      edit_user GET    /users/:id/edit(.:format)                 users#edit
           user GET    /users/:id(.:format)                      users#show
                PATCH  /users/:id(.:format)                      users#update
                PUT    /users/:id(.:format)                      users#update
                DELETE /users/:id(.:format)                      users#destroy

因此,您可以看到 for tweets#edittweets#showtweets#updatetweets#destroy,:user_id是不需要的。这是因为shallow: true

您可以在指南中阅读有关浅嵌套的更多信息。


推荐阅读