Topic: RAND

SO IF I HAVE THIS:

class SponsorsController < ApplicationController

  def index
    @random_sponsors = Sponsor.find(:first, :order => ["RAND()"])
    @sponsors = Sponsor.all_sponsors
    @bands = Band.all_bands
  end

end


AND THIS IN MY HTML

<div id="featured_sponsor">
  <p class="title"><%= random_sponsor.name %></p>
  <p><%=h random_sponsor.description %></p>
</div>



AND THIS HAPPENS:


undefined local variable or method `random_sponsor'


IS THERE SOMETHING WRONG WITH MY RAND() CODE?

THANK YOU

MK

Re: RAND

in the controller method you have @random_sponsors (plural), while in the view you have @random_sponsor.name (singular)

My RoR journey  -- thoughts on learning RoR and lessons learned in applying TDD and agile practices.

Re: RAND

IT STILL DOES THIS:

undefined local variable or method `random_sponsor'

THE PLURALITY THING, I DO NOT BELIEVE IS THE ISSUE. I USE THESE TOO:

<% for band in @bands %>
  <%= band.homepage_url %>
<% end %>

THIS WAS WORKING BEFORE INCLUDING THE CODE IN THE ORIGINAL POST INSIDE THE CONTROLLER

mk

Re: RAND

Don't forget the @ sign in your views:

<div id="featured_sponsor">
  <p class="title"><%= @random_sponsors.name %></p>
  <p><%=h @random_sponsors.description %></p>
</div>

P.S. Please lighten up on the caps.

Railscasts - Free Ruby on Rails Screencasts

Re: RAND

You need the '@' before the 'random_sponsor' in the view.  And yes you need the plurality (actully the name, the plurality has nothing to do with it) of the controller and view to match in this case. 

In the @bands example, the controller assigned to @bands, you then have a loop over @bands, with each individual loop iteration assining to 'band'.  Thus band is a local variable and is available.

In the @random_sponsors case, the controller assign to the plural instance variable -- so that's all the view has access to.  If you use the same looping construct that created local singular variables from the plural instance variable, it might hace worked...  However there is no reason to loop over a single element list...

My RoR journey  -- thoughts on learning RoR and lessons learned in applying TDD and agile practices.

Re: RAND

BRILLIANT!

(sorry, one last blast with caps.)

This makes perfect sense and truly gets me closer to understanding the complexities of RoR. I am a stupid print/web designer who kind of enjoys the more coded things in life.

The caps was just to separate my own words from code. My apologies.

Thanks so much it really works!

I am super stoked right now.

mk