On 20 January 2015 at 09:04, Javix <[email protected]> wrote:
> I wonder id it is normal behaviour that when building an assosiation 'build'
> method , the returned size of association array changes despite the objet is
> nt saved yet ? Here is a short exampe to illustrate that:
>
> class User < ActiveRecord::Base
>     has_many :posts, dependent: :destroy
> end
>
> class Post < ActiveRecord::Base
>     belongs_to :user
> end
>
> Nothing complex until now. When I play with that in the console:
> Loading development environment (Rails 4.2.0)
> irb(main):001:0> user = User.first
>   User Load (0.0ms)  SELECT  "users".* FROM "users"  ORDER BY "users"."id"
> ASC LIMIT 1
> => #<User id: 1, name: "toto", created_at: "2015-01-16 11:18:41",
> updated_at: "2015-01-16 11:18:41">
> irb(main):002:0> user.posts.size
>    (0.0ms)  SELECT COUNT(*) FROM "posts" WHERE "posts"."user_id" = ?
> [["user_id", 1]]
> => 0
> irb(main):003:0> post = user.posts.build(title: 'ruby')
> => #<Post id: nil, user_id: 1, title: "ruby", created_at: nil, updated_at:
> nil>
> irb(main):004:0> user.posts.size
> => 1
> irb(main):005:0>
>
> As you see the size of user posts is changed by 1. Why ? The post is not
> still saved to the database. The user_id is nil. I had to apply some
> validation before adding a new post tp ths user, that's why I wonder if it
> is normal adn how to display just the existing User posts without using
> 'select' for example.

You have not saved it to the database but you have added it to the
users posts in memory.  If you reload user it will revert to 0, and
you will lose the built post.  If you want to check what it is in the
database then fetch the user to a new variable.
user1 = User.first
then user1.posts.size will be 0

Colin

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/rubyonrails-talk/CAL%3D0gLu0360Qzt8WnjBh%3DX9e%3D54mbYBYM%2BeJ1ozWizPqu75_uA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to