Randomly pick photo from User model ruby -


the schema ruby on rails app below. filling home page , want randomly pick photo(s) random existing user feature on home page.

i have tried lot of things in home controller , cant seem right...

class homecontroller < applicationcontroller    def index     @featured = user.find(:all, :limit => 4, :order => 'random()')     @users = user.find(:all)     user_count = user.count()     offset = rand(0..(user_count-1))     @my_user = user.find(:all, :limit => 1, :offset => offset )   end end 

i have tried following no success:

@photo = user.find(:order => 'random()').photo  @user = user.find(:all, :limit => 1, :order => 'random()') @photo = photo.find(@user) 

i errors such: couldn't find photo id=6

how go without pointing nil location/non-existent photo...?

activerecord::schema.define(:version => 20130513143229)    create_table "photos", :force => true |t|     t.datetime "created_at", :null => false     t.datetime "updated_at", :null => false     t.string   "image"     t.integer  "user_id"   end    create_table "roles", :force => true |t|     t.string   "name"     t.integer  "resource_id"     t.string   "resource_type"     t.datetime "created_at",    :null => false     t.datetime "updated_at",    :null => false   end    create_table "users", :force => true |t|     t.string   "email",                  :default => "", :null => false     t.string   "encrypted_password",     :default => "", :null => false     t.string   "reset_password_token"     t.datetime "reset_password_sent_at"     t.datetime "remember_created_at"     t.integer  "sign_in_count",          :default => 0     t.datetime "current_sign_in_at"     t.datetime "last_sign_in_at"     t.string   "current_sign_in_ip"     t.string   "last_sign_in_ip"     t.datetime "created_at",                             :null => false     t.datetime "updated_at",                             :null => false     t.string   "name"     t.string   "avatar"     t.string   "image"   end 

you should able accomplish offset clause.

first, total number of users have.

user_count = user.count()

then random number between 0 , number - 1.

offset = rand(0..(user_count - 1))

then select offset random user

my_user = user.find(:all, :limit => 1, :offset => offset)

to random subset of pictures random user use same procedure, couple caveats. change :limit how many pictures want, make sure random offset number_of_pictures - picture_limit, , make sure when count pictures, counting subset want select (photo.count(:user_id => my_user.id)). isn't random, because picture subset in whatever order database wants put in, @ least subset start @ random place set should different.


Comments

Popular posts from this blog

Change php variable from jquery value using ajax (same page) -

Pull out data related to my apps from Android Play Store and iOS App Store -

How can I fetch data from a web server in an android application? -