【问题标题】:How to separate (new,create,delete) actions and show action in Rails for a blog?如何在 Rails 中为博客分离(新建、创建、删除)操作并显示操作?
【发布时间】:2014-03-27 05:59:42
【问题描述】:

我正在尝试建立一个博客,但遇到了一些问题。该博客有一个单独的仪表板,有自己的布局/dashboard。想象一下,我有一个名为 post 的模型。在博客中,博客文章 URL 将类似于 /post/hello-world。通常很容易添加、编辑和删除这些帖子。我只需在路线中添加resources :posts 并像/post/new 一样进行编辑。

但我需要将新建、创建和销毁操作移至仪表板。所以它就像dashboard/post/new。我试图通过在破折号控制器中添加新操作并尝试发布到post 创建操作来做到这一点。它失败了。尝试仅更改创建(发布)和新操作的路径,但也失败了。

我的问题是,在这种情况下,做事的标准方法是什么?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4


    【解决方案1】:

    您可以在路由中使用:only/:except 选项

    resources :posts, :except => [:new, :create, :destroy]
    scope 'dashboard' do
      resources :posts, :only => [:new, :create, :destroy]
    end
    

    rake 路由的输出

          posts GET    /posts(.:format)               posts#index
      edit_post GET    /posts/:id/edit(.:format)      posts#edit
           post GET    /posts/:id(.:format)           posts#show
                PUT    /posts/:id(.:format)           posts#update
                POST   /dashboard/posts(.:format)     posts#create
       new_post GET    /dashboard/posts/new(.:format) posts#new
                DELETE /dashboard/posts/:id(.:format) posts#destroy
    

    注意:如果您想要单独的仪表板控制器,您可以使用namespace 'dashboard' 而不是scope

    【讨论】:

    • 我已经有一个仪表板控制器。所以,我的路线会是这样的get 'dashboard', to: 'dash#show'resources :posts, :except => [:new, :create, :destroy]namespace 'dashboard' doresources :posts, :only => [:new, :create, :destroy]end 对吗?如果我错了,请纠正我。
    【解决方案2】:

    我建议在后期控制器中设置仪表板布局

    class PostsController < ApplicationController
    
     layout "dashboard"
    
     def create
      # your code for create
     end
    
    end
    

    【讨论】:

      猜你喜欢
      • 2023-03-23
      • 1970-01-01
      • 2013-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多