如何检查查询中是否有任何结果并添加 if/else 条件

how to check if there are any results in a query and add an if/else condition

在我的 home_controller 中,我必须显示几个列表。

我有这个:

  def subscriptions
    @movies = current_user.followed_movies
                         .limit(12)
                         .order('movies.last_news DESC NULLS LAST').decorate  
  end

  def watched
    @movies = current_user
             .watched_movies
             .order_by_watched_date
             .limit(12).decorate
  end

我想在 def 订阅中添加一个 if 条件。 例如

  def subscriptions
    @movies = if this query has no results... current_user.followed_movies
                         .limit(12)
                         .order('movies.last_news DESC NULLS LAST').decorate
               else
                  to show the movies in the def watched
               end 
 end

怎么办?

不清楚你在找什么,但我想你的意思是:

"if the subscriptions query is empty, use the watched query instead".

我可能会这样做:

def set_movies
  @movies = subscriptions
  @movies = watched if subscriptions.empty?
  @movies = @movies.limit(12).decorate
end

def subscriptions
  current_user.followed_movies.order_by_last_news
end

def watched
  current_user.watched_movies.order_by_watched_date
end

然后在 user.rb 我可能会添加:

scope :order_by_last_news, -> { order('movies.last_news DESC NULLS LAST') }

我们可以创建作用域,但为了简单起见,可以创建两个单独的方法,如下所示:

def movies_followed
   current_user.followed_movies
end

def movies_watched
   current_user.watched_movies
end

然后我们可以在下面def subscriptions中使用这两种方法,如下所示:

def subscriptions
   @movies = 
       if movies_followed
          movies_followed.limit(12).order('movies.last_news DESC NULLS LAST').decorate
       else
          movies_watched.order_by_watched_date.limit(12).decorate
       end
end

希望,它符合您的要求...