A
A
Anton Ipatov2014-12-19 20:19:46
MongoDB
Anton Ipatov, 2014-12-19 20:19:46

How can I optimize the output of feed_entries in a category?

Hello there are three models source.rb, feed_entry.rb and category.rb.
source.rb

class Source
include Mongoid::Document

field :title, type: String

has_many :feed_entries, dependent: :destroy
belongs_to :category, touch: true
end

feed_entry.rb
class FeedEntry
include Mongoid::Document

field :name, type: String
belongs_to :source, touch: true
validates :source_id, presence: true
end

category.rb
class Category
include Mongoid::Document

field :name, type: String

has_many :sources, dependent: :destroy
end

How can I optimize the output of feed_entries in category ?
At the moment it's done like this:
categories_controller.rb
class CategoriesController < ApplicationController
def show
@category = Category.find(params[:id])
@sources = @category.sources.all
end
end

show.html.erb
<%= @category.name %>

<% @sources.each do |source| %>
  <% source.feed_entries.each do |feed_entry| %>
    <%= link_to feed_entry.name, feed_entry %></p>
    <%= feed_entry.source.title %>
  <% end %>
<% end %>

The project uses mongoid 4 and rails 4

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
Boris Penkovsky, 2014-12-21
@IpatovAnton

for the Category class

def feed_entries
    FeedEntry.in(source_id: sources.map(&:id))
end

and then immediately in the view
@category.feed_entries

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question