簡體   English   中英

在Ruby on Rails中顯示類別文章和標簽

[英]Displaying categories article and tags in Ruby on Rails

我想顯示一個類別鏈接以列出該類別的所有文章。 我在此項目中使用了Mongodb / Mongoid,但是我不確定自己是否做得很好。

文章模型

class Article
  include Mongoid::Document
  include Mongoid::Timestamps

 field :title, type: String
  field :content, type: String

  belongs_to :user
  #kategorie
  belongs_to :article_category

物品控制者

  class ArticlesController < ApplicationController
    def article
    @article = Article.order_by(created_at: 'desc').page params[:page]
  end

  def view_article
    @article = Article.find(params[:id])
  end
end

文章類別模型

class ArticleCategory
  include Mongoid::Document
  include Mongoid::Timestamps


  field :name, type: String

  has_many :articles


end

路線

  get 'article', to: 'articles#article'
  get 'article/:id', to: 'articles#view_article', as: 'view_article'

我想做類似的事情。 Article ,下面是類別鏈接。 我單擊此鏈接,然后看到該類別中的文章列表。 我應該成為ArticleCategory控制器嗎? 那么categories路線呢?

由於您具有ArticleCategory模型,因此可以,擁有ArticleCategoryController是有意義的。 對於路由,我會讓您的routes.rb文件看起來像這樣:

resources :article_categories do
  resources :articles, shallow: true
end

這樣,路由就被嵌套了(因為articles belong_to article_categories),但是您可以直接訪問文章,而不必知道其父類別。 要閱讀有關路由(尤其是嵌套)的更多信息,請查看this

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM