ruby on rails - Display all posts from a certain category -


i'm looking display posts category on page, have posts & category models linked habtm relationship. want able click link on index.html.erb , go through page lists posts belong category.

do need create controller category , new routes?

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 (my current way display category each post)

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

** update **

after answer routes have been produced below.

          category_posts    /categories/:category_id/posts(.:format)          posts#index                      post   /categories/:category_id/posts(.:format)          posts#create    new_category_post    /categories/:category_id/posts/new(.:format)      posts#new   edit_category_post    /categories/:category_id/posts/:id/edit(.:format) posts#edit        category_post    /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    /categories(.:format)                             categories#index                      post   /categories(.:format)                             categories#create         new_category    /categories/new(.:format)                         categories#new        edit_category    /categories/:id/edit(.:format)                    categories#edit             category    /categories/:id(.:format)                         categories#show                      patch  /categories/:id(.:format)                         categories#update                      put    /categories/:id(.:format)                         categories#update                      delete /categories/:id(.:format)                         categories#destroy 

you can nest posts inside categories

resources :categories   resources :posts end 

this make routes categories/1/posts , url helpers category_posts_path(1) 1 category id. in posts controller, have params[:category_id] available can lookup category , fetch posts. like

if params[:category_id]   @category = category.find params[:category_id]   @posts = @category.posts else   @posts = post.all end  

Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -