0
所以我有一個郵政模型和一個用戶模型。專屬於用戶和用戶可以有很多帖子:如何在Rails 4中做user.posts這樣的東西?
=> #<Post id: 1, title: "First post", content: "first post", created_at: "2013-07-07 17:30:55", updated_at: "2013-07-07 17:30:55", user_id: 1>
1.9.3-p0 :015 > user
=> #<User id: 1, name: "Jano", email: "[email protected]", created_at: "2013-07-07 17:31:41", updated_at: "2013-07-07 17:31:41">
post.user
工作至今:
1.9.3-p0 :016 > post.user
=> #<User id: 1, name: "Jano", email: "[email protected]", created_at: "2013-07-07 17:31:41", updated_at: "2013-07-07 17:31:41">
1.9.3-p0 :017 >
但是當我做user.posts
:
1.9.3-p0 :017 > user.posts
Post Load (0.6ms) SELECT "posts".* FROM "posts" WHERE "posts"."user_id" = ? [["user_id", 1]]
=> #<ActiveRecord::Associations::CollectionProxy []>
1.9.3-p0 :018 >
我不明白的帖子但奇怪的是#<ActiveRecord::Associations::CollectionProxy []>
的事。
我想我從來沒有在Rails 3上看到過這個。有什麼不同的方式在Rails 4中調用user.posts
?
哦謝謝,但實際應用中我沒有添加to_a吧? – alexchenco
奇怪的是,我仍然得到一個空數組:'Post Load(0.6ms)SELECT「posts」。* FROM「posts」WHERE「posts」。「user_id」=? [[「user_id」,1]] => []' – alexchenco
空數組意味着沒有該用戶的帖子user_id –