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.
*Rails version: 4.2.0, Ruby 2.1.5*
Thank you.
--
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/d36227b6-ee89-4f48-86b1-1db9fe6c20fc%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.