简体   繁体   中英

Generate random from rails model

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!

Use the following as a starting point, and modify the limit to match the number of cards you want to display.

Get two random elements from a RoR model

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM