Kamil Mrozek
Kamil Mrozek

Reputation: 41

How to find articles which belongs to category in Ruby on rails

i want to display only a articles which belongs to the category. For example: user click on the category and he is getting a list of all articles in this category.

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

Routes

  resources :article_categories do
  resources :articles, shallow: true
  end

ArticleCategories Controller

class ArticleCategoriesController < ApplicationController

  def index
   @article = Article.find
  end

    end

In the article view i'm displaying all articles and in articles_categories view i want to show the specific posts. So how should the controler look like( i'm now talking about ArticleCategoriesController .) I tried using a Article.find_by(name: 'JS') but it is not working. I'm looking for some help :)

Upvotes: 0

Views: 855

Answers (1)

WeezHard
WeezHard

Reputation: 2022

You can do this:

class ArticleCategoriesController < ApplicationController
    def index
        @category = ArticleCategory.find(params[:id])
        @articles = @category.articles
    end
end

Because you ArticleCategory model has_many Articles, you can do @categoy.articles

UPDATE

Now, to show the articles on the view, you must interact te @articles collection (array) like this:

<% @articles.each do |article| %>
    <%= article.title %><br>
    <%= article.body %><br><br>
<% end %>

UPDATE 2

You can do this to create a link for a category:

<%= link_to category.name, category %>

Advise:

I think that you have a basic issues. I recommend you to read something like this:

Will give you a good foundation

Upvotes: 1

Related Questions