Kamil Mrozek
Kamil Mrozek

Reputation: 41

NoMethodError, undefined method in my controller Ruby on Rails

I'm getting NoMethodError at /article

undefined method 'article_category' for Mongoid::Criteria

Article model

class Article
  include Mongoid::Document
  include Mongoid::Timestamps

  field :title, type: String
  field :content, type: String

  belongs_to :user
  #kategorie
  belongs_to :article_category

Article controler

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 model

class ArticleCategory
  include Mongoid::Document
  include Mongoid::Timestamps


  field :name, type: String

  has_many :articles


end

Article_category controller

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

routes

  get 'article', to: 'articles#article'
  get 'article/:id', to: 'articles#view_article', as: 'view_article'
  resources :article_categories do
  resources :articles, shallow: true
end

Is there everything good with my category controller ?

In my article view i'm displaying it in this way.

<%= link_to @article.article_category.name, @article.article_category -%>

Upvotes: 0

Views: 531

Answers (2)

mu is too short
mu is too short

Reputation: 434665

Your problem is in ArticlesController#article:

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

That sequence of order_by and page calls is just building a query so you have a Mongoid::Criteria in @article rather than the single Article instance that your template apparently expects.

I'm not sure but the presence of view_article and its article/:id route suggests that your article method should look like:

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

and the corresponding view should iterate over @articles to display each article.

Upvotes: 1

Norm Fasey
Norm Fasey

Reputation: 1

It looks like it is complaining that it does not know how to hook up the relationship between Article and ArticleCategory. It may not be able to infer the name of the class in Article?

Try adding the class_name to the definition of the relationship.

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"

Upvotes: 0

Related Questions