2012-04-29 68 views
0

您好我有關聯一個小問題,我使用Rails 3.2的工作,我想創建一個特殊的博客,這個博客有許多部分,這部分有很多的文章和一篇文章屬於一個類別。所以,我的型號有:模特協會

class Article < ActiveRecord::Base 
    belongs_to :section 
    belongs_to :category 

class Category < ActiveRecord::Base 
    has_many :articles 

class Section < ActiveRecord::Base 
    has_many :article 

belongs_to的部分,因此文章,在routes.rb中:

resources :sections do 
    resources :articles 
end 

耙路線:

     POST /sections/:section_id/articles(.:format)   articles#create 
new_section_article GET /sections/:section_id/articles/new(.:format)  articles#new 
edit_section_article GET /sections/:section_id/articles/:id/edit(.:format) articles#edit 
    section_article GET /sections/:section_id/articles/:id(.:format)  articles#show 
        PUT /sections/:section_id/articles/:id(.:format)  articles#update 
        DELETE /sections/:section_id/articles/:id(.:format)  articles#destroy 
      sections GET /sections(.:format)        sections#index 
        POST /sections(.:format)        sections#create 
     new_section GET /sections/new(.:format)       sections#new 
     edit_section GET /sections/:id/edit(.:format)      sections#edit 
      section GET /sections/:id(.:format)       sections#show 
        PUT /sections/:id(.:format)       sections#update 
        DELETE /sections/:id(.:format)       sections#destroy 

所以我的問題是如何創建一個Categories_controller索引並顯示操作。 表明,屬於這一類的文章,並有相應的文章路徑意見的link_to(類別#顯示)。

回答

1

假設你需要嵌套的路線,以滿足您的域模型(例如:文章需要的顯示不同的是根據它們是否在類別或部分的上下文中查看),那麼您可以創建另一組嵌套路由,如下所示:

的routes.rb

resources :categories, only: [:index, :show] do 
    resources :articles 
end 

,將成立的航線類別來查找您的類別和文章,但你將不得不叉你的邏輯在你的ArticlesControllerparams[:category_id]params[:section_id]像這樣:

class ArticlesController < ApplicationController 
    def index 
    if params[:section_id] 
     # handle section_articles_path to display articles by section 
    elsif params[:category_id] 
     # handle category_articles_path to display articles by category 
    else 
     # handle articles_path to display all articles (assuming you have resources :articles in routes) 
    end 
    end 
    # ... 
end 

基於類別顯示文章的鏈接將使用爲您創建的生成路線幫助程序方法。

類別/ show.html.erb

<ul> 
    <% @category.articles.each do |article| %> 
    <li><%= link_to article.title, category_article_path(@category, article) %></li> 
    <% end %> 
</ul> 

然後,您可以,當然,重構視圖代碼來呈現集合作爲自己的部分,而不是手動迭代,但我會離開它在那個現在...

如果你並不需要以不同方式處理上下文(訪問通過對部分類別的文章),我建議只設置了三個基本途徑(:articles:sections:categories )並從那裏出發。

+0

謝謝,我想我的邏輯是昨天失敗了,我一直在尋找無類路由訪問的文章。謝謝您的回答! – 2012-04-30 01:01:10

0

這是非常簡單的 match 'catagories' => "catagories#index"match 'catagories/show/:id' => "catagories#show" 在表演動作@articles = Article.where("category_id",params[:id])

@articles = Article.where("category_id",params[:id])這將解決你的目的