I'm currently working on an online store for a sports card website using Ruby on Rails. In a sidebar on the homepage, I want to randomly generate cards from my products model (which I have already created via scaffold). How would I go about doing so? Any help would be much appreciated!
Asked
Active
Viewed 322 times
0
-
You'll have to be more specific than that if you want to get good answers. Do you want to select random products? – Robin Nov 27 '11 at 04:13
-
Yes. Sorry. My products model is compiled of sports cards since it is a sports card website, so yes, I am looking to generate random products. – TopChef Nov 27 '11 at 04:27
2 Answers
1
Use the following as a starting point, and modify the limit
to match the number of cards you want to display.
1
Your question is very generic, so I'm going to make a couple of assumptions here. (1) I'm assuming you can fit most all your products into memory. (2) The random products only need to be updated every few hours or so.
First write a method that selects some products from your model randomly: (Also read How do I pick randomly from an array? on how to get random items):
products = Products.find(:all)
(1..5).each do |n|
selectedProduct = products[rand(myarray.length)]
selectedProduct.shouldAppearOnHomePage = true
selectedProduct.save
end
You can run this method (perhaps with /script/rails exec) every now-and-then. It will set the shouldAppearOnHomePage on new random products.
Then all that is left to do is to query the database where shouldAppearOnHomePage is true and display those products.