简体   繁体   English

如何列出与某个类别相关的所有文章?

[英]How to list all the articles related to a certain category?

In my RoR app I have a problem with listing all items of a certain category. 在我的RoR应用程序中,我在列出某个类别的所有项目时遇到问题。 Here is 2 models: 这是2个型号:

class Article < ApplicationRecord
  belongs_to :category

and 

class Category < ApplicationRecord
  has_many :articles
end

and my Category controller method : 和我的类别控制器方法:

  def show
    @articles = @category.articles
    @category = Category.find(params[:id])
  end

In db i have relation beetween categories and articles: 在db中我有类别和文章之间的关系:

create_table "articles", force: :cascade do |t|
    t.string "title"
    t.text "text"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string "category_id"
  end

  create_table "categories", force: :cascade do |t|
    t.string "name"
    t.text "desc"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

And in my article index view page have code where on link ("Category") name I want to show all articles of certain category 并且在我的文章索引视图页面中有代码,其中链接(“类别”)名称我想显示某些类别的所有文章

  <td>
    <% if article.category %>
      <%= link_to article.category.name, category_path %>
    <% end %>
  </td>

But I receive error 但我收到错误

No route matches {:action=>"show", :controller=>"categories"}, missing required keys: [:id]

您必须提供响应id方法的idcategory对象才能生成正确的链接:

<%= link_to article.category.name, category_path(article.category) %>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM