wyc
wyc

Reputation: 55343

How to do stuff like user.posts in Rails 4?

So I have a Post model and a User model. Post belongs to user and User can have many 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 works so far:

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 > 

But when I do 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 > 

I don't get the posts but a strange #<ActiveRecord::Associations::CollectionProxy []> thing.

I think I never saw this on Rails 3. Is there any different way of calling user.posts in Rails 4?

Upvotes: 0

Views: 81

Answers (1)

Dylan Markow
Dylan Markow

Reputation: 124479

If you want the actual results inside the console, you should add to_a on to the end:

user.posts.to_a

Upvotes: 1

Related Questions