Given these ActiveRecord table definitions:
create_table :parents do |t|
end
create_table :children do |t|
t.references :parent
end
And the corresponding models:
class Parent < ActiveRecord::Base
has_many :children
end
class Child < ActiveRecord::Base
belongs_to :parent
end
When I create an unsaved record which has an unsaved association:
parent = Parent.new
parent.children << Child.new
And ask for the number of associated records:
parent.children.count
=> 0
Then the result is 0. I expected 1.
I wish for the count I get to reflect both unsaved and saved associated records. How can I get that count?
Versions:
You need to use #size rather than #count. As you (well, I) discovered, #count ignores records in memory. #size considers both saved and unsaved records.
Here are the methods you can use to test for the existence or count of associated records:
count
count only considers what in the database, ignoring anything in
memory. This issues an SQL statement every time, ignoring any
caching.
size
To get the total number of saved and unsaved associated records, use
size. This method differs from length in that it does not force
associated records to be loaded into memory.
length
To load all associated records into memory and then count all records, use length. The total count of both saved and unsaved records will be returned.
exists?
To find out if there are any records on disk, ignoring the presence of
any in memory, use exists?. This issues an SQL statement every time,
ignoring any caching.
a github comment by Carlos Antonio Dasilva:
length with always load the objects and use Array#length
count will always do a SQL count
size will check whether the collection is loaded, and use it, otherwise will do a count.
size should give you the correct value in this case I think.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With