我在/ article
收到NoMethodErrorMongoid :: Criteria的未定义方法'article_category'
文章模型
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
ArticleCategory模型
class ArticleCategory
include Mongoid::Document
include Mongoid::Timestamps
field :name, type: String
has_many :articles
end
Article_category控制器
class ArticleCategoriesController < ApplicationController
def category # Give the view all categories to list
@categories = ArticleCategory.order("created_at DESC")
end
def show
@category = ArticleCategory.find(params[:id])
end
end
路由
get 'article', to: 'articles#article'
get 'article/:id', to: 'articles#view_article', as: 'view_article'
resources :article_categories do
resources :articles, shallow: true
end
我的类别控制器有什么用的吗?
在我的文章视图中,我以这种方式显示它。
<%= link_to @article.article_category.name, @article.article_category -%>
答案 0 :(得分:1)
您的问题出在ArticlesController#article
:
def article
@article = Article.order_by(created_at: 'desc').page params[:page]
end
order_by
和page
来电的序列只是构建一个查询,因此您在Mongoid::Criteria
而不是单个@article
实例中有一个Article
模板显然期望。
我不确定view_article
及其article/:id
路线的存在表明您的article
方法应如下所示:
def article
@articles = Article.order_by(created_at: 'desc').page params[:page]
# ------^
end
并且相应的视图应该遍历@articles
以显示每篇文章。
答案 1 :(得分:0)
看起来它抱怨它不知道如何连接Article和ArticleCategory之间的关系。它可能无法在文章中推断出类的名称?
尝试将class_name添加到关系的定义中。
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_name: "ArticleCategory"