Render different show pages with category in ruby on rails

99封情书 提交于 2020-01-03 05:07:06

问题


I need render different show pages for my blog posts.

I have 3 different categories : themes, snippets, projects.

Each blog post must related with those three categories.

If anyone click post(assume related category is snippets), it display in different show...etc... It is same for other categories.

How it is possible with conditional statements.


回答1:


you can make routes like:

resources :posts, except:[:show]
get 'posts/:id/cat/:category' , to:'posts#show', as: :show

you have to create partial for categories as follows:

app/views/posts/_themes.html.erb

app/views/posts/_snippets.html.erb

app/views/posts/_projects.html.erb

then in controller's show action.

controllers/posts_controller.rb





 def show
   @post = Post.find(params[:id])
   @category = params[:category]
   ...
 end

Then render that category in show page.

views/posts/show.html.erb

...
<%= render  '#{@category}'%>



回答2:


Just one show method and you can render different views conditionally and simple render works for you, you can use below code:

Just render with HTML file name if file is in same controller's view

if @post.theme?
  render 'themes'
elsif @post.snippet?
  render 'snippets'
else
  render 'projects'
end



回答3:


I would start with this, then refactor for avoiding repetition

categories_controller.rb

def themes
  #@posts = Post.where(category_id: 1)
  ...
  render layout: themes
end

def snippets
  #@posts = Post.where(category_id: 2)
  ...
  render layout: snippets
end

def projects
  #@posts = Post.where(category_id: 3)
  ...
  render layout: snippets
end



回答4:


You can do something like this:

models/post.rb

def category
   @category ||= ... #returns category name
end

controllers/post_controller.rb

def show
  @post = Post.find(id)
  @category = @post.category
  ...
end

views/posts/show.html.erb

...
<%= render "types/#{@category}" %>
...

Also you can render specified template from controller if you don't have any common parts for categories




回答5:


You can use rails partial to achieve this:

to know more about partial refer Rails Partial

you can create partial for categories as follows:

app/views/categories/_themes.html.erb

app/views/categories/_snippets.html.erb

app/views/categories/_projects.html.erb

in show page of categories you can modify the show page as follows

class CategoriesController < ApplicationController
  ...
  def show
    ...
    render params[:category]
  end
  ...
end

Now when you call show page pass a param category which denotes the type of category which you want to show

if you want to show category snippets then the params will be params[:category] = 'snippets' this will look for partial inside categories view.



来源:https://stackoverflow.com/questions/43558477/render-different-show-pages-with-category-in-ruby-on-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!