Twiddr
Twiddr

Reputation: 297

List of IDs from associated model

I have 3 models: Users, Articles and Comments.

Textbook case :)

I would like to make a list of Article IDs where the User has made Comments on. How do I do that?

I've tried variants of User.find(1).comments.articles_ids in the console but that gives me a undefined method error.

I'm sure it's simple, but I cant't figure it out :)

Thanks!

Upvotes: 0

Views: 52

Answers (1)

Jakob S
Jakob S

Reputation: 20125

One way of doing it, that works with your current setup:

user.comments.collect(&:article_id).uniq

Alternatively I guess you could add a has_many :through to User:

class User < ActiveRecord::Base
  has_many :articles, :through => :comments
end

then you can get the ids via user.articles.collect(&:id) (perhaps also user.article_ids, but I'm not sure about that).

Upvotes: 1

Related Questions