显示特定类别的所有帖子

时间:2015-03-28 16:24:27

标签: ruby-on-rails ruby ruby-on-rails-4 has-and-belongs-to-many

我希望在一个页面上显示某个类别的所有帖子,我目前有帖子&由HABTM关系链接的类别模型。我希望能够点击index.html.erb上的链接,然后转到列出属于该特定类别的所有帖子的页面。

我是否需要为类别和新路线创建控制器?

Post.rb

class Post < ActiveRecord::Base
  has_and_belongs_to_many :categories
  belongs_to :user
end

Category.rb

class Category < ActiveRecord::Base
  has_and_belongs_to_many :posts
end

Index.html.erb(我目前显示每个帖子类别的方式)

<% post.categories.each do |category| %>
  <% category.posts.each do |post| %>
    <%= link_to category.name, post_url(post) %>
  <% end %>
<% end %>

**更新**

在制作了答案路线后,如下所示。

          category_posts GET    /categories/:category_id/posts(.:format)          posts#index
                     POST   /categories/:category_id/posts(.:format)          posts#create
   new_category_post GET    /categories/:category_id/posts/new(.:format)      posts#new
  edit_category_post GET    /categories/:category_id/posts/:id/edit(.:format) posts#edit
       category_post GET    /categories/:category_id/posts/:id(.:format)      posts#show
                     PATCH  /categories/:category_id/posts/:id(.:format)      posts#update
                     PUT    /categories/:category_id/posts/:id(.:format)      posts#update
                     DELETE /categories/:category_id/posts/:id(.:format)      posts#destroy
          categories GET    /categories(.:format)                             categories#index
                     POST   /categories(.:format)                             categories#create
        new_category GET    /categories/new(.:format)                         categories#new
       edit_category GET    /categories/:id/edit(.:format)                    categories#edit
            category GET    /categories/:id(.:format)                         categories#show
                     PATCH  /categories/:id(.:format)                         categories#update
                     PUT    /categories/:id(.:format)                         categories#update
                     DELETE /categories/:id(.:format)                         categories#destroy

3 个答案:

答案 0 :(得分:1)

必须回答:

在您的分类模型中:

def to_param
  name
end

但请接受Logan的答案是正确的,因为他解决了你原来的问题。

答案 1 :(得分:0)

您可以在类别中嵌套帖子

resources :categories do
  resources :posts
end

这会生成categories/1/posts之类的路由和category_posts_path(1)之类的URL帮助,其中1是类别ID。然后在您的帖子控制器中,您将有params[:category_id]可用,可以查找该类别,然后获取帖子。像

这样的东西
if params[:category_id]
  @category = Category.find params[:category_id]
  @posts = @category.posts
else
  @posts = Post.all
end 

答案 2 :(得分:0)

def index 
 if params[:category_id]
  @posts = Post.where("category_id = ?", params[:category_id])
 else
   @posts = Post.all
 end 
end

Logan答案的替代方法,因为在某些情况下可能无法正常工作。