Showing posts with label else. Show all posts
Showing posts with label else. Show all posts

Sunday, June 5, 2011

Rendering a different view using partials

Remember yesterday when I was talking about having a good day followed by a bad day with Rails? Looks like today is going to be a good day!

Something I've been wanting to do with Chorenivore is change the view so it only displays the information for a task (Done, Task, Description, Created) if there actually IS a task. Otherwise, this information shouldn't be displayed, right?

This morning I woke up with the idea of creating a couple of partials and then rendering them with an if else statement. So right away I got started. I broke out the code displayed in the view into 'yestask', then creating a partial called 'notask' that didn't display anything but a method for creating a new task.

Here's what I tried at first:

<% if @task.blank? %>
<%= render 'notask' %>
<% else %>
<%= render 'yestask' %>
<% end %>


This code doesn't throw an error, but it doesn't do what I want. In this case, it bypasses 'yestask' altogether and only renders 'notask'. I dug around in Tasks controller and realized I should be writing the code like so:

<% if @tasks.blank? %>
<%= render 'notask' %>
<% else %>
<%= render 'yestask' %>
<% end %>


I get why this version works, because it's checking if there are any instances of @task. I'm still not sure why just calling @task.blank? didn't work. Is it because @task is a method, while @tasks is defined in the controller as Task.all?

Definitely feels good to make some progress, even if I'm not 100% sure about why the method I tried first didn't work.

Another general question: Is using partials in this way a good practice? I kind of feel like I understand partials pretty well, so every problem appears to be something that can be solved with partials. There's a metaphor buried in there somewhere.