Rails 只提供“belong_to"的记录. [英] Rails only give records that "belong_to"

查看:37
本文介绍了Rails 只提供“belong_to"的记录.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 author 模型、一个 article 模型和一个 metric 模型.作者有很多文章,文章有很多指标.

I have a author model, a article model and a metric model. Author has many articles and article has many metrics.

在我的 articles_controller 的显示操作中没有我有 @articles = Article.where(author_id: params[:id]) 它将文章限制为那个作者.我可以对指标做类似的事情吗?有没有一种方法可以说像 @metrics = Metric.WHICHBELONGSTO(@articles)?

No in my articles_controller's show action I have @articles = Article.where(author_id: params[:id]) which limits the articles to the ones by that author. Can I do something similar for the metrics? Is there a rails way to say something like @metrics = Metric.WHICHBELONGSTO(@articles)?

或者,我可以传入一组允许的 ID 吗?像 @metrics = Metric.where(article_id 是 @articles ID 的一部分?)

Alternatively can I pass an array of allowed IDs in? like @metrics = Metric.where(article_id is part of @articles IDs?)

推荐答案

如果 Article 有很多 Metric,您只需通过该关联获取这些记录:

If Article has many Metrics, you would simply fetch those records through that association:

@metrics = Article.find(article_id).metrics

如果您有要查找指标的文章集合(例如在批量更新作业中),您还可以执行以下操作:

If you have a collection of articles you would like to find metrics for, such as in a batch update job, you could also do the following:

@metrics = Metric.where(article_id: @articles).all

ActiveRecord 将自动构建正确的查询.

ActiveRecord will build the correct query automatically.

这篇关于Rails 只提供“belong_to"的记录.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆