我有一张用户表和等级表,不建立关系 用户表中有经验字段,等级表中也有相应的经验字段,我想通过用户表中的经验字段判断用户等级,除了用 if else if 等一个个比较经验所对应的等级表,还有其他的好方法吗
适当的冗余有必要(这个可能都不是冗余),我觉得 lv 这个字段可以有
class User < ActiveRecord::Base def level Level.where(:经验 => self.经验) end end
不是这个意思吗
2 楼的做法就可以,建议加上 cache,启动进程的时候,就缓存所有 level,然后写个简单的函数。
等级表里的数据是有限的,全部取出来 cache 吧,2 楼的做法列表的时候会 N+1
应该是这个意思
def level if exp > 100 1 elsif exp > 200 2 elsif exp > 500 3 end end
求简化。
def level Level.where('exp <= ?', self.exp).order('exp').last end
是这个意思?
@Rei 是这个意思求简化
LEVEL_TABLE = [100, 200, 500] def level LEVEL_TABLE.index { |exp| exp > self.exp } end
def exp_to_lv(exp, map) map.each_with_index do |limit, level| return level if exp < limit end raise 'exp not in map' end map = [ 0, #达到1级所需经验 10, #达到2级所需经验 100, #达到3级所需经验 # ........... ] puts "exp: 15, lv: #{exp_to_lv(15, map)}"
@lululau,@Rei看了大家写的方法现在,终于想明白了!谢谢