Lonely road

Conditional Instance Variables

Monday January 16, 2017

Perhaps you are in a situation where you want to show a different index of posts depending on if the user is logged in or not. Instead of writing condition statements in the view, it makes more sense to set up this logic in the controller.

For example, let's say you want to show all posts to the user if user_signed_in?, but only published posts if not signed in. One approach is to use conditional instance variables in the controller. Here we can define the variable @posts that will provide all of the active posts. This is a good default for anonymous users, as it will prevent them from viewing anything that is still in an unpublished state.


# posts_controller.rb

def index
  @posts = Post.all.active.order('posts.created_at DESC')
  if user_signed_in?
    @posts = Post.all.order('posts.created_at DESC')
  end
end

However, if user_signed_in?, @posts will be overwritten to represent all posts, regardless of if they are active or not. The signed in user will see a list of all posts, published and unpublished. And this will keep the view clean by using a single instance variable, as follows:


# index.html.erb

<% @posts.each do |post| %>
  // Your code here
<% end %>
Robinheadshotsquare

Written by Robin Hamill

Robin is an independent web application and ecommerce developer living in Toronto. He builds intuitive and functional web apps that engage users and solve problems. He's also excited about climbing rocks, travelling and learning all the things. 💎⛪️

Back