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

时间:2015-08-05 11:04:19

标签: ruby-on-rails ruby mongodb mongoid

我在/ 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

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

2 个答案:

答案 0 :(得分:1)

您的问题出在ArticlesController#article

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

order_bypage来电的序列只是构建一个查询,因此您在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"