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

时间:2019-04-06 18:55:24

标签: ruby-on-rails ruby-on-rails-4

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

怎么办?

2 个答案:

答案 0 :(得分: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') }

答案 1 :(得分: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

希望,它可以满足您的需求...