您好我的协会有一点问题,我正在使用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 section,在routes.rb中:
resources :sections do
resources :articles
end
Rake Routes:
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。 显示属于该类别的文章,并在文章路径的视图(类别#show)中有link_to。
答案 0 :(得分:1)
假设您确实需要嵌套路由来适应您的域模型(例如,文章需要根据是否在类别或部分的上下文中查看它们而显示不同),那么您可以创建另一组嵌套像这样的路线:
<强>的routes.rb 强>
resources :categories, only: [:index, :show] do
resources :articles
end
这将设置路线以按类别查找您的类别和文章,但您必须在ArticlesController
上params[: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
,{ {1}})并从那里开始。
答案 1 :(得分:0)
非常简单
match 'catagories' => "catagories#index"
和match 'catagories/show/:id' => "catagories#show"
在show action @articles = Article.where("category_id",params[:id])
@articles = Article.where("category_id",params[:id])
这将解决您的目的