我有一个post
模型和posts
控制器,其属性为format
,因此id喜欢根据此属性拆分视图,如果格式为{foo.com/blog/xxx
如果格式为blog
,则{1}}和foo.com/news/xxx
。
news
resources :posts
我可以轻松地为索引视图这样的东西,但我不确定show route
def index
@posts = Post.where(draft: 'false').order(publish_date: :desc)
end
def show
@post = Post.find_by!(slug: params[:id])
end
get '/new', to: 'posts#news'
答案 0 :(得分:0)
要指明节目路线,您需要将ID作为路线中的参数传递。
get '/blog/:id' => 'posts#blogs'
我想这就是你要找的东西。
答案 1 :(得分:0)
您可以尝试这种方式:
在routes.rb
中创建两种不同的方法,它们将位于您想要拥有“PostsController
”的唯一一个控制器中,并对params
属性进行验证通过@post
方法的每个show
,例如:
class PostsController < ApplicationController
def show
@post = Post.find(params[:id])
if @post.format == 'news'
redirect_to news_index_path
elsif @post.format == 'blog'
redirect_to blog_index_path
end
end
def blog_index
end
def news_index
end
...
然后在routes.rb
中指定每个方法的路径,就像您在show
方法中所做的那样,以便使用redirect_to
方法:
get '/blog/:id', to: 'posts#blog_index', as: 'blog_index'
get '/news/:id', to: 'posts#news_index', as: 'news_index'
这是,当您传递格式属性等于@post
的{{1}}时,您将被重定向到blog
,这将加载blog_index_path
视图blog_index
中的posts
文件夹。当app/views/posts
为@post.format
时,似乎会发生一些事情。
news
每次你必须从├── blog_index.html.erb
├── index.html.erb
├── news_index.html.erb
└── show.html.erb
0 directories, 4 files
转到下一条路线时,路线会有很小的延迟和非常快速的变化。
我已经制作了repo,以便您查看其工作原理。