45
52

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ActiveRecord::Associations::CollectionProxy

Last updated at Posted at 2013-07-16

Rails4では、has_many関連の中身はActiveRecord::Associations::CollectionProxyが入っている。
ドキュメント
http://api.rubyonrails.org/classes/ActiveRecord/Associations/CollectionProxy.html

app/model/user.rb
class User < ActiveRecord::Base
  has_many :comments
end
app/model/comment.rb
class Comment < ActiveRecord::Base
  belongs_to :user
end
db/schema.rb
create_table "comments", force: true do |t|
  t.integer  "user_id"
  t.datetime "created_at"
  t.datetime "updated_at"
end

create_table "users", force: true do |t|
  t.string   "comment"
  t.datetime "created_at"
  t.datetime "updated_at"
end
irb(main):001:0> user = User.create
irb(main):002:0> user.comments.create
irb(main):004:0> p user.comments
#<ActiveRecord::Associations::CollectionProxy [#<Comment id: 8, user_id: 2, created_at: "2013-07-16 07:58:18", updated_at: "2013-07-16 07:58:18">]>

#中身を取り出すときはtarget
irb(main):005:0> p user.comments.target
[#<Comment id: 8, user_id: 2, created_at: "2013-07-16 07:58:18", updated_at: "2013-07-16 07:58:18">]
=> [#<Comment id: 8, user_id: 2, created_at: "2013-07-16 07:58:18", updated_at: "2013-07-16 07:58:18">]

#数をかぞえるときはcount。毎回SQLが発行される
irb(main):006:0> p user.comments.count
=> 1

#sizeでも数えられる。sizeは一回ロードすればSQLが発行されないっぽい
irb(main):007:0> p user.comments.size
=> 1
45
52
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
45
52

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?