【问题标题】:Ruby on Rails shallow nesting resourcesRuby on Rails 浅层嵌套资源
【发布时间】:2021-05-31 19:51:27
【问题描述】:

我正在尝试找出实现浅层路由嵌套的 Ruby-on-Rails 方法,它允许我跟踪最顶层的资源。

假设我们在config/routes.rb 中设置了如下浅层嵌套路由:

resources :article, shallow: true do
  resources :comments
end

resources :comments, shallow: true do
  resources :likes
end
     

你会怎么说从comments/3/likes 重定向到/articles/1/comments,因为article_id 在参数中不可用,所以最好将article_id 放在会话哈希中(当文章通过控制器中的回调?)并以这种方式检索它?我尝试查看 Rails 指南,虽然这解释了浅层资源嵌套,但并没有超出此范围。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-6


    【解决方案1】:

    假设一篇文章有​​多个cmet,并且评论属于一篇文章,您可以通过评论访问该文章:

    comment = Comment.find(params[:comment_id])
    comment.article_id 
    

    【讨论】:

    • 为了避免额外的查询,comment.article_id 更适合这里。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-25
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 2021-06-01
    • 2015-11-30
    • 2014-03-19
    相关资源
    最近更新 更多