0
votes

I have a object User and object Post. A User has_many Posts and a Post belongs_to a User. I can access the posts a user has using syntax like:

posts = @user.posts

However, I want to generate an array of ids of the posts a user owns, without looping through each one. Ideally, I'd like to do this:

ids = @user.posts.id

However, I get an error, saying that id is an invalid method for ActiveRecord--etc etc...

Is there any way to neatly do this without having to do a loop like:

ids = []
posts = @user.posts
posts.each |post| do
   ids << post.id
end
4

4 Answers

3
votes

Rails provides a native method for this:

@user.post_ids

Essentially, you can refer to the ids of a has_many association using <singular association name>_idspattern.

2
votes

Try with ids = posts.map(&:id) or ids = posts.map{|p| p.id }

You can also try with ids = posts.pluck(:id)

0
votes

You Can also use collect. Collect returns the Array.

ids = @user.posts.collect(&:id)
0
votes

try this :

@ids = @user.posts.map{|x| x.id }

Hope it will help.