0

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?

Krzychu
  • 241
  • 2
  • 4
  • 12
  • Does users.count stay the same? Or is it users.length that stays the same? –  Sep 26 '12 at 20:25
  • @new_user.save see: [Build Method][1] [1]: http://stackoverflow.com/questions/783584/ruby-on-rails-how-do-i-use-the-active-record-build-method-in-a-belongs-to-rel – Paul Meier Sep 26 '12 at 20:54

1 Answers1

1

current_client.users.count makes 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.length will give you the count using Ruby.

current_client.users.count # => 2
current_client.users.length # => 2
current_client.users.build
current_client.users.count # => 2
current_client.users.length # => 3
  • OK, thanks for explanation. To avoid this situation I changed my new method to something like: `current_client_dup = current_client.dup @user = current_client_dup.user.build` – Krzychu Sep 27 '12 at 07:32