0

I'm still really new to Rails and working on a practice project lab and I ran into an issue where the view was rendering really slow. Any and all help would be appreciated!

I also received this error:

SystemStackError (stack level too deep):
  
app/models/blogger.rb:23:in `popular_post'
app/views/bloggers/show.html.erb:13:in `_app_views_bloggers_show_html_erb__247812415140953454_70240453389320'

Gemfile

gem 'rails', '~> 5.1.6'
gem 'sqlite3'
gem 'puma', '~> 3.7'
gem 'sass-rails', '~> 5.0'
gem 'uglifier', '>= 1.3.0'
gem 'faker'
gem 'coffee-rails', '~> 4.2'
gem 'turbolinks', '~> 5'
gem 'jbuilder', '~> 2.5'

group :development, :test do
  gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
  gem 'capybara', '~> 2.13'
  gem 'selenium-webdriver'
end

group :development do
  gem 'web-console', '>= 3.3.0'
  gem 'listen', '>= 3.0.5', '< 3.2'
  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.0'
end

gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

My classes are Blogger, Destination, and Post (Blogger -< Post >- Destination). Below is the code for the Blogger model, show page, and controller (I didn't work on code for anything else yet, except the Blogger index but works and is just a list)

blogger.rb

class Blogger < ApplicationRecord
    has_many :destinations
    has_many :posts, through: :destinations
    validates :name, uniqueness: true
    validates :age, numericality: { greater_than: 0, message: ": You're Too Young" }
    validates :bio, length: { :minimum => 30 }

    def self.average_age
        ages = self.all.sum do |blogger|
            blogger.age
        end
        (ages / self.all.count)
    end

    def total_likes
        self.posts.sum do |post|
            post.likes
        end
    end

    def popular_post
        self.posts.max_by do |a|
            a.likes
        end
    end

    def top_five
        self.destinations.sort_by do |destination|
            destination.post_count
        end.take(5)
    end
end

blogger show page

<h1> <%= @blogger.name %> </h1>

<br />
<p> Age: <%= @blogger.age %> </p>
<br />
<br />
<p> Bio: <%= @blogger.bio %> </p>
<br />


<br />

<%= link_to @blogger.popular_post.title, post_path(@blogger.popular_post) %>

<br />
<%= @blogger.top_five %>

blogger controller

class BloggersController < ApplicationController
   
    def index
        @bloggers = Blogger.all
    end

    def show
        @blogger = Blogger.find(params[:id])
    end
    

    def new
        @blogger = Blogger.new
    end

    def create
        @blogger = Blogger.create(blogger_params) 
        if @blogger.valid?
            @blogger.save
            redirect_to blogger_path(@blogger)
        else
            flash[:my_errors] = @blogger.errors.full_messages
            redirect_to new_blogger_path
            # render :new
        end
    end
    
    private

    def blogger_params
        params.require(:blogger).permit(:name, :bio, :age)
    end
    
    
    
end
4
  • 2
    can you please show the post.rb too?
    – Fernand
    Aug 10, 2020 at 23:43
  • Is it "very slowly", or "not at all, because it raises a SystemStackError"?
    – Tom Lord
    Aug 11, 2020 at 7:34
  • You haven't shown us the full stack trace (in particular, which part is getting stuck in a recursive loop and causing a stack overflow??), nor the full code (in particular, what's in post.rb?), so it's hard to make a guess at the root cause of the problem.
    – Tom Lord
    Aug 11, 2020 at 7:37
  • 1
    To fix this problem you might need to understand what this error actually means. This error is caused by a recursive call to some method that does not stop being called. Have a look at ruby-doc.org/core-2.5.0/SystemStackError.html. You need to figure out what method is causes this error. The error message says that it starts at line 23 in blogger.rb in the method popular_post. That is where a.likes is called where a is a Post object. So I guess you need to have a look at the likes method in the Post class.
    – Smek
    Aug 11, 2020 at 7:40

2 Answers 2

1

I think that you need to modify this method

def popular_post
        self.posts.max_by do |a|
            a.likes
        end
    end

max_by is a method for an Enumerable class and you call it on a Post class, so this will not work properly. I would suggest that you use something like posts.order('likes DESC').first if likes is an Integer.

Also tiny hint you don't need to use all this self in an object and in class methods. Rails would assume that you call it on an object if this is an object method or you call it on a relation if this is a class method.

0

The methods total_likes, popular_post and top_five all work by assuming your associations are "arrays" (enumerations). While this works, definitally for smaller examples, it is less optimal. Because working on an array also requires the complete array to be loaded from the database first, and then do your calculations locally on a complete set (in memory). A database is optimally suited to perform such tasks (querying).

For instance, top_five can better be written to sort on the database and then only fetch the 5 first (most popular).

def top_five
  destinations.order(post_count: :desc).limit(5)
end 

(this is assuming that :post_count is an actual field in the database.

Similarly we can improve the other methods:

def total_likes
  posts.sum(:likes)
end

just use the database: this will start a single query to return the sum of likes for all the posts of the blogger.

def popular_post
  posts.order(likes: :desc).limit(1).first
end

We sort on descending likes and the select the first one. The limit 1 tells we only want to retrieve one item, but this still returns an array, so we want the first returned item.

This should improve your performance.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.