【发布时间】: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