繁体   English   中英

NoMethodError,我的控制器Ruby on Rails中的未定义方法

[英]NoMethodError, undefined method in my controller Ruby on Rails

我在/ article处收到NoMethodError

Mongoid :: 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

文章类别模型

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 -%>

您的问题在ArticlesController#article

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

order_bypage调用的顺序只是建立一个查询,因此您在@article有一个Mongoid::Criteria ,而不是模板显然希望的单个Article实例。

我不确定,但是view_article及其article/:id路由的存在表明您的article方法应如下所示:

def article
  @articles = Article.order_by(created_at: 'desc').page params[:page]
  # ------^
end

并且相应的视图应遍历@articles以显示每篇文章。

似乎在抱怨它不知道如何建立Article与ArticleCategory之间的关系。 可能无法推断Article中的类名称?

尝试将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"

暂无
暂无

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

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