一个帖子'有两条不同路线的资源?

时间:2016-01-19 01:43:29

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

我想使用一个帖子获得两条(或更多条)不同路线的所有宁静路线。控制器。我在多品牌网站上工作,并且我试图记下重复的代码。

brand1/blog/:id
brand2/blog/:id

现在我有:

resources :posts, :path => "brand1/blog"
     get 'brand2/blog' => 'posts#brand2_index'

我可以使用@ post.brand参数正确显示两个博客,但各个帖子的网址最终都是针对brand1。

我对rails和编程非常陌生,所以我肯定会遗漏一些基本的东西。

非常感谢任何帮助。谢谢!

3 个答案:

答案 0 :(得分:2)

处理此问题的一种简洁方法是使用范围。您可以像这样定义您的路线:

scope ':brand_name' do
  resources :posts, path: 'blog'
end

无需复制控制器操作。在您的控制器中,您将获得params[:brand_name]的品牌。生成的路线如下:

    posts GET        /:brand_name/blog(.:format)                     posts#index
          POST       /:brand_name/blog(.:format)                     posts#create
 new_post GET        /:brand_name/blog/new(.:format)                 posts#new
edit_post GET        /:brand_name/blog/:id/edit(.:format)            posts#edit
     post GET        /:brand_name/blog/:id(.:format)                 posts#show
          PATCH      /:brand_name/blog/:id(.:format)                 posts#update
          PUT        /:brand_name/blog/:id(.:format)                 posts#update
          DELETE     /:brand_name/blog/:id(.:format)                 posts#destroy
     page GET        /pages/*id                                      high_voltage/pages#show

答案 1 :(得分:1)

这通常包含在nested resources中:

#config/routes.rb
resources :brands, path: "", only: [] do
   resources :posts, path: "blog", only: [:index, :show] #-> url.com/:brand_id/blog/:id
end

由于您未使用brands作为资源,因此您需要使用scope(无需控制器):

#config/routes.rb
scope :brand do
   resources :posts, path: "blog", only: [:index, :show] #-> url.com/:brand/blog/:id
end

然后你可以在你的参数中找到:brand

#app/controllers/posts_controller.rb
class PostsController < ApplicationController
   def show
     @brand = Brand.find params[:brand]
     @post  = @brand.posts.find params[:id]
   end
end

-

如果您想确保只接受有效品牌作为路线,您就会想要使用自定义约束:

#config/routes.rb
scope :brand, constraints: BrandExists do
    resources :posts, path: "blog", only: [:index, :show] #-> url.com/:brand/blog/:id
end

#lib/brand_exists.rb
module BrandExists

    def initializer(router)
        @router = router
    end

    def self.matches?(request)
        Brand.exists? request.path.split("/").first
    end

end

Very good ref here

答案 2 :(得分:0)

尝试按以下方式嵌套资源,然后运行rake routes以查看您提供的内容。

resources :posts do
    get 'brand1/blog', to: "posts#brand1_index"
    get 'brand2/blog', to: "posts#brand2_index"
end

贾斯汀

相关问题