J.Luca
J.Luca

Reputation: 208

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

in my home_controller, I have to show several lists.

I have this:

  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

I want to add an if condition in the def subscriptions. For example

  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

How to do?

Upvotes: 1

Views: 52

Answers (2)

DevPro
DevPro

Reputation: 511

We can create scopes but for the simplicity, two separate methods can be created as below:

def movies_followed
   current_user.followed_movies
end

def movies_watched
   current_user.watched_movies
end

And then we can use those two methods in the below def subscriptions as below:

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

Hope, it suites your requirement...

Upvotes: 0

stephan.com
stephan.com

Reputation: 1518

it's not clear exactly what you're looking for, but I think you mean:

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

I'd probably do that like this:

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

and then in user.rb I might add:

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

Upvotes: 1

Related Questions