繁体   English   中英

通过Rails使用查询has_many

[英]Using query has_many through rails

我有3个模型,

文章

belongs_to :category
belongs_to :author

作者

has_many :articles
has_many :categories, through: :articles

类别

has_many :articles
has_many :authors, through: :articles

这就是我要做的

撰文/ show.html.erb

<h5>Recent Articles</h5>
<table>
 <thead>
  <tr>
   <th>Judul Artikel</th>
   <th>Kategori</th>
  </tr>
 </thead>
 <tbody>
  <% Article.all.each do |author| %>
   <tr>
    <td><%= author.judul_artikel %></td>
    <td><%= author.category.nama_kategori %></td>
   </tr>
  <% end %>
 </tbody>
</table>

我想做的是在表中显示author / id时,仅显示存在ID的类别和文章。

我不知道如何在这里使用查询

假设您想要的是与该作者相关的文章:

使用哈希条件,您可以将“文章”模型更好地划分为与作者相关的文章:

<% Article.where(author_id: @author.id).each do |author| %>
  <tr>
   <td><%= author.judul_artikel %></td>
   <td><%= author.category.nama_kategori %></td>
  </tr>
<% end %>

但是有一个更好的解决方案。 由于使用的是show操作,因此应传递一个实例变量(例如@author )。 然后可以将其关联方法用作对象@author.articles

<% @author.articles.each do |author| %>
  <tr>
   <td><%= author.judul_artikel %></td>
   <td><%= author.category.nama_kategori %></td>
  </tr>
<% end %>

暂无
暂无

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

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