mardi 26 septembre 2017

Understanding rails size vs count, and why .size doesn't work in view?

When I use the method .count, it works just fine and accurately shows the number of posts. When I try .size, it throws an error. Why is this?

My static_controller.rb code (with COUNT as a method)

class StaticController < ApplicationController

def index
@post_count = Post.count
@user_count = User.count
end

index.html.erb (with COUNT as a method)

<div>
      <p> <%= @post_count %> </p>
</div>

When I change the instances of .count to size, I get this error in the local server:

NoMethodError at / undefined method `size' for #

index - app/controllers/static_controller.rb, line 4

Why is this? Is .size not a built in method for rails? If not, how can I fix this issue?

Also, am I correct in understanding that .size is more performant if a counter_cache is applied to the model that the method is being applied to? For example, if my post.rb model has a section where counter_cache is declared, does that automatically make it more fast/performant?

Aucun commentaire:

Enregistrer un commentaire