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

问题描述 投票:1回答:2

在我的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

怎么做?

ruby-on-rails ruby-on-rails-4
2个回答
0
投票

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

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

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


1
投票

目前尚不清楚你究竟想要什么,但我认为你的意思是:

“如果订阅查询为空,请改为使用观察的查询”。

我可能会这样做:

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') }
© www.soinside.com 2019 - 2024. All rights reserved.