Rails only give records that “belong_to”

拜拜、爱过 提交于 2020-01-05 12:57:36

问题


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

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)?

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


回答1:


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 will build the correct query automatically.




回答2:


 @metrics = Metric.where(article_id: @articles.map(&:id))

Should work




回答3:


coreyward's answer is fine but here's another way to fetch metrics given the author_id assuming that Metric belongs_to :article

@metrics = Metric.joins(:article).where(articles: { author_id: params[:id] })



回答4:


You can include the referenced metrics in one ActiveRecord statement by simply expanding the one you are already using:

@articles = Article.where(author_id: params[:id]).includes(:metrics).all

This loads the articles by the specified author and includes all metrics related to these articles in one go. You then have the objects in one tidy structure instead of having to juggle and map the articles to their metrics separately.

Access them like this (in ERB for example):

<% @articles.each do |article| %>
  <%= article.title %>
  <%= article.text %>
  <% article.metrics.each do |metric| %>
    <%= metric.value %>
  <% end %>
<% end %>

The advantage here is that all relevant metrics are preloaded. If you simply call article.metrics without previously loading them using the includes method, your server would need to access the database every time you want to use the metrics of each article, slowing down the page loading times considerably.



来源:https://stackoverflow.com/questions/22690148/rails-only-give-records-that-belong-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!