Search code examples
ruby-on-railscycle

Rails: Cycle Producing Same Result Every Time


I'm trying to create a zebra-striped series of divs with the following code:

= content_tag_for(:div, conversation.receipts_for(current_user), :class => cycle("odd", "even")) do |receipt|
  %p=receipt.content

In theory, the class names should cycle between "receipt odd" and "receipt even" for each row. Instead, I get "receipt odd" every single time. I've tried using unordered lists and tables as well, but they don't work properly either. Any idea what's going on?


Solution

  • This can't work, the way you've written it. cycle is called once at the time you call content_tag_for, and it returns "odd". It is that value, "odd", that is passed into content_tag_for, not the function cycle. Unless content_tag_for accepts a block/lambda for its style argument, you cannot do what you are trying to do.

    In essence, you're calling a function and passing in the return value of a second function:

    func1( func2() )
    

    The best way to handle this is via collection rendering.

    In your view:

    = render conversation.receipts_for(current_user)
    

    In a separate partial, probably app/views/receipts/_receipt.html.haml:

    = div_for receipt, :class => cycle('odd', 'even')
      %p=receipt.content