簡體   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