简体   繁体   English

关联模型的ID列表

[英]List of IDs from associated model

I have 3 models: Users, Articles and Comments. 我有3个模型:用户,文章和评论。

  • Articel has many Comments. Articel有很多评论。
  • Comments belongs to Article. 评论属于文章。
  • User has many comments. 用户有很多评论。

Textbook case :) 课本案例:)

I would like to make a list of Article IDs where the User has made Comments on. 我想列出用户对其发表评论的文章ID的列表。 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. 我在控制台中尝试了User.find(1).comments.articles_ids的变体,但这给了我一个未定义的方法错误。

I'm sure it's simple, but I cant't figure it out :) 我敢肯定这很简单,但是我无法弄清楚:)

Thanks! 谢谢!

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 : 另外,我猜你可以给User添加一个has_many :through

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). 那么您可以通过user.articles.collect(&:id)获取ID(也许也可以是user.article_ids ,但我不确定)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM