Random default value for integer in database for each instance?

跟風遠走 提交于 2019-12-13 04:37:22

问题


I'm using this system for voting content in my rails app: https://github.com/twitter/activerecord-reputation-system

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

If I store something like rand(5..12) it will only pick a random default value one time, how do I get a random default value for every different 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


回答1:


Use a before_create filter.

class RsEvaluation < ActiveRecord::Base

  before_create :update_value

  def update_value
    self.value = rand(5..12)
  end

end

However; Since Evaluation is not your own model, but one from a library, try opening the class and patching it:

module ReputationSystem

  class Evaluation < ActiveRecord::Base
    before_create :update_value

    def update_value
      self.value = rand(5..12)
    end
  end

end

This would be placed in your config/initializers folder.



来源:https://stackoverflow.com/questions/18621396/random-default-value-for-integer-in-database-for-each-instance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!