0

I’m using Rails 4.2.7. I have this association …

class MyObject < ActiveRecord::Base
  has_many :my_object_times

and

class MyObjectTime < ActiveRecord::Base
  belongs_to :my_object

However I notice when I’m looking at a particular record in Rails, it is always giving me “0” for the size of my count when checking how many child items I have. For instance, when I execute this

puts "result name: #{result.name} id: #{result.id} MyObject times: #{result.my_object_times.size}"

I get

result name: 53rd Annual Lincoln Classic id: 79eaf6ea-284f-4421-82eb-39c3e9450f8e MyObject times: 0

But when I log in to my PostGres 9.5 database and run a query, I see plenty of child records …

myproject=> select count(*) FROM my_object_times where my_object_id = '79eaf6ea-284f-4421-82eb-39c3e9450f8e';
 count 
-------
   490

How can I force an accurate count when checking how many children I have?

Dave
  • 15,639
  • 133
  • 442
  • 830
  • 2
    First, change `belongs_to :MyObject` to `belongs_to :my_object` and check again – a14m Dec 03 '16 at 22:24
  • Hi, Gvae this a go but got the same result. – Dave Dec 04 '16 at 17:40
  • use `result.my_object_times.count` instead of `result.my_object_times.size` count issue an SQL count statement while size is an array method that will not issue the SQL query in that case if you used `result.my_object_times(true).size` it might work since the relation array is evaluated (passing true to relation force it to evaluate) – a14m Dec 04 '16 at 17:58
  • check this for more info http://stackoverflow.com/questions/6083219/activerecord-size-vs-count – a14m Dec 04 '16 at 18:04
  • Using `size` should still query the database unless `result.my_object_times` has already been loaded. We'd have to see what else you're doing with `result` to see if that's the issue. Can you tell (in a Rails console, for example) whether the database is being queried? As @mad_raz said, you can use `count` if you want to force it to run a query no matter what. – Max Dec 04 '16 at 18:34

0 Answers0