【问题标题】:How to list all the articles related to a certain category?如何列出与某个类别相关的所有文章?
【发布时间】:2019-03-20 13:42:36
【问题描述】:

在我的 RoR 应用程序中,我无法列出某个类别的所有项目。这里有 2 个模型:

class Article < ApplicationRecord
  belongs_to :category

and 

class Category < ApplicationRecord
  has_many :articles
end

和我的类别控制器方法:

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

在数据库中,我在类别和文章之间有关系:

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

在我的文章索引视图页面中有代码,我想在链接(“类别”)名称上显示某个类别的所有文章

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

但我收到错误

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

【问题讨论】:

  • @jvillian 名为@category 的实例变量在 CategoriesController 中定义,OP 在文章索引视图中添加链接。

标签: ruby-on-rails


【解决方案1】:

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

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

【讨论】:

  • 上帝保佑你)它有帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-12-11
  • 1970-01-01
  • 1970-01-01
  • 2013-05-12
  • 2014-04-07
  • 1970-01-01
  • 2018-08-16
相关资源
最近更新 更多