Tuesday, August 9, 2011

If and Unless Methods in Rails

Sometimes shit just works.

Sometimes I sit down to code for an hour or two and everything I try either works right away, or is broken in such a way that the first fix I attempt works.

Today was one of those days! I had some minor successes straight off the bat, such as moving Delete methods into Edit methods, moving Edit methods into the Menu partial along with navigation and changing the Show method for Characters in the Index view to display character.name instead of a generic 'Show'.

But here's the big triumph of the heart tonight.

You may recall in my last post I was talking about how in the menu partial I didn't want to display pages that didn't apply to all characters. I don't want a spell tab in the menu for a character that doesn't learn spells, for example. So I figured out a way to solve this problem, and the really beautiful thing is the solution was maybe two lines of code. Why did I think this would be such a big deal?

Here's what I had originally:

<%= link_to_unless_current 'Special Abilities', character_specials_path(@character) %>

Changing this code so the Special Abilities page only shows up if it's been created is easy enough:

<%= link_to_unless_current 'Special Abilities', character_specials_path(@character) if @character.specials.exists? %>

But then I run into a problem. With the previous code, it was simple enough to create a Special Ability, since you just clicked on the Special Ability link and the show page would render the form, allowing you to create a Special Ability, or edit a previous Special Ability. So obviously I need to land a link to create that page somewhere.

The Character show page seems a logical choice, since it will exist before a Special Ability will, and a Special Ability's existence will depend upon a Character's existence, right? So let's wire that up:

<%= link_to 'Create Special Abilities Page', character_specials_path(@character) unless @character.specials.exists? %>

Making pretty good use of those if and unless methods!

I know Rails programmers often talk about how they can't believe something is so easy to do with Rails, but shit, I can't believe this was so easy to do. And it feels good to make this much progress on my own, because I feel like a lot of the time I'm just asking for help. This is a pretty good indicator that I'm figuring out how things work, where things go and how to make Rails sing and dance for me.

No comments:

Post a Comment