Let’s say I have this simple method in my helper that helps me to retrieve a client:
def current_client
@current_client ||= Client.where(:name => 'my_client_name').first
end
Now calling current_client returns this:
#<Client _id: 5062f7b851dbb2394a00000a, _type: nil, name: "my_client_name">
Perfect. The client has a few associated users, let’s look at the last one:
> current_client.user.last
#<User _id: 5062f7f251dbb2394a00000e, _type: nil, name: "user_name">
Later in a new method I call this:
@new_user = current_client.user.build
And now, to my surprise, calling current_client.user.last returns
#<User _id: 50635e8751dbb2127c000001, _type: nil, name: nil>
but users count doesn’t change. In other words – it doesn’t add the new user but one user is missing… Why is this? How can I repair it?
current_client.users.countmakes a round trip to the database to figure out how many user records are associated. Since the new user hasn’t been saved yet (it’s only been built) the database doesn’t know about it.current_client.users.lengthwill give you the count using Ruby.