On Oct 16, 2008, at 4:38 PM, command0 wrote:
> > Hey guys, > > Ok, so right now I am working on generating a random number with ruby > or rails? > > So far I have gathered that I somehow or another want to use the > rand() helper to so, but not sure how to do it to achieve what I am > trying to accomplish. > > What I am trying to do, is have a 6 digit number randomly generated, > and then tag it to a course name, for this > training portal I am writing. This is mostly so I can locate courses > in the mysql database without typing in the exact title. Why do you want a random number? Why not just use the primary key integer that Rails will give you for free? You don't have to do any work to generate it and the only downside is that if I see /course/1 I imagine I could try /course/2 and it would work, but if you're not trying to "hide" these courses that shouldn't be an issue. > @random = self.rand(99999).to_s.center(5, rand(9).to_s) One problem with this is that you may end up with a duplicated value sometime down the road. So you'll have to check for uniqueness even when doing this. -philip > I've been trying to search the web for possible solutions, and I found > one that I thought would work at: > http://www.coryperry.com/2008/09/02/generating-a-random-number-with-ruby/ > > But it didn't seem to work so well, as its real vague on how he is > implementing it in his app. > > I was trying to use it in an action called new that goes to a page > called new.html.erb in order to create a new course record. Here is > the snippet for the new action in the courses_controller file. > > -------- > > def new > @course = Course.new > @random = self.rand(99999).to_s.center(5, rand(9).to_s) > > respond_to do |format| > format.html # new.html.erb > format.xml { render :xml => @course } > end > end > > -------- > > So from there on the new.html.erb page, I tried to call the random > variable at the top of page, declaring it as: > > <% @random => :course_num %> > > Now, for clarification, course_num is the database field I created, > that is set to the int data type. > > So essentially, I am trying to have a random number generated when I > go to create a new course record, and then store that output to a > variable that would then save it to the database field. > > Thanks again in advance for your help. > > Justin > > --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to rubyonrails-talk@googlegroups.com To unsubscribe from this group, send email to [EMAIL PROTECTED] For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en -~----------~----~----~----~------~----~------~--~---