Random default value for integer in database for each instance?

I use this system for voting content in the rails application: https://github.com/twitter/activerecord-reputation-system

Is there a way to make the default score for any voted item a random number for each instance.

If I store something like rand (5..12), it will only select a random default value once, how do I get a random default value for every other row or field?

create_table "rs_evaluations", :force => true do |t| t.string "reputation_name" t.integer "source_id" t.string "source_type" t.integer "target_id" t.string "target_type" t.float "value", :default => 0.0 t.datetime "created_at", :null => false t.datetime "updated_at", :null => false 

end

0
source share
1 answer

Use the before_create filter.

 class RsEvaluation < ActiveRecord::Base before_create :update_value def update_value self.value = rand(5..12) end end 

Nonetheless; Since Evaluation is not your own model, but another from the library, try opening a class and fixing it:

 module ReputationSystem class Evaluation < ActiveRecord::Base before_create :update_value def update_value self.value = rand(5..12) end end end 

This will be placed in your config/initializers folder.

+3
source

Source: https://habr.com/ru/post/953368/


All Articles