仅在满足特定条件时显示内容? [英] Only show content when certain criteria is met?

查看:57
本文介绍了仅在满足特定条件时显示内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有我想要完成的最佳实践......

I'm wondering if theres a best practice for what I'm trying to accomplish...

首先我们有模型类别、类别、has_many 帖子.

First we have the model categories, categories, has_many posts.

现在假设,用户添加帖子.

Now lets say, users add posts.

现在,我有一个页面,我只想按类别显示当前用户的帖子.

Now, I have a page, that I want to display only the current user's posts by category.

假设我们有以下类别:A、B 和 C

Lets say we have the following categories: A, B, and C

用户 1,已在类别 A 和 B 中发帖.

User 1, has posted in Categories A and B.

在我看来,我有类似的东西:

In my view I have something like:

@categories.each do |category|

   category.name

   @posts.each do |post|
   if post.category_id==category.id

     post content here

    end
    end


end

这里的问题是,我要显示空类别以及确实有内容的类别.

The problem with this, is I'm going to show the empty category, as well as the categories that do have content.

有没有更有效的方法来解决这个问题?因为我不想显示空类别.

Is there a more efficient way of going about this? As I don't want to show the empty categories.

最好的,艾略特

更新:

所以我一直在尝试使用此代码:

So I've been trying to use this code:

在大多数情况下,它几乎就在那里.问题是,如果在其中输入了任何帖子,它仍然会显示一个空类别(即使当前用户没有在该类别中输入帖子.

For the most part its almost there. The issue is, it will still show an empty category if any posts have been entered in it at all (even if the current user has not input posts into that category.

所以问题归结为:

如何使以下循环只计算当前用户在该类别中的帖子?

How do I make the following loop only count posts in the category from the current user?

推荐答案

<% @categories.select {|cat| cat.posts.count > 0}.each do |category| %>
  <%= category.name %><br/>
  <% category.posts.select {|post| post.user == current_user}.each do |post| %>
    <%= post.content %><br/>
  <% end %>
<% end %>

这将呈现每个类别的任何帖子,然后是属于当前用户的类别中每个帖子的内容.不过,您可能希望在控制器中进行初始选择,以保持视图干净.

This renders each category with any posts, then the content for each post within the category belonging to the current user. You'd probably want to do the initial selection in the controller though, to keep the view clean.

这篇关于仅在满足特定条件时显示内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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