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。显示属于该类别的文章,并在文章路径的views(Category#show) 中有一个link_to。

4

2 回答 2

1

假设您确实需要嵌套路由来适应您的域模型(例如,文章需要根据它们是在类别还是部分的上下文中查看而有所不同),那么您可以像这样创建另一组嵌套路由:

路线.rb

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

这将设置路线以按类别查找您的类别和文章,但您将不得不在您的ArticlesControlleronparams[: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)并从那里开始。

于 2012-04-29T14:40:08.370 回答
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])这将解决您的目的

于 2012-04-29T08:48:08.927 回答