Rails中集中管理数据字典的方法

首先创建一个数据字典的model

ruby script/generate model dictionary


然后在create_dictionaries中添加字典表的定义:


def self.up
create_table dictionaries do |t|
t.string :category # 分类,用以区别不同的字典
t.string :display # 字典的值,用于显示
t.string :store # 字典的键,用于存储,根据习惯,也可以用t.integer :store
t.integer :parent_id # 自身关联,用以多级字典
end
end


然后在Dictionary模型中增加类方法


def self.find_dictionary(conditions)
dict = Dictionary.find(:all, :conditions => "category = \'#{conditions}\'", :select => "display, store")
dict.collect {|d|[d.display, d.store]}
end

这个函数返回一个多重数组,便于在view中直接使用字典

假设字典中包含以下数据:

1, "EDUCATION", "初中以下", "1", nil
2, "EDUCATION", "高中", "2", nil
3, "EDUCATION", "专科", "3", nil
4, "EDUCATION", "本科", "4", nil
5, "EDUCATION", "硕士以上", "5", nil


在Member模型中将使用到这个字典,因此我们在member_controller.rb中添加

before_filter :load_dictionary, :include => [:index, :new, :edit, :show]


然后在Controller的protected端写以下代码:

def load_dictionary
@education_dictionary = Dictionary.find_dictionary("EDUCATION")
end


然后在new或者edit中选择字典的部分写入

<% f.select, @education_dictionary, :prompt => "请选择学历" %>


在index或者show中写入

<%= @education_dictionary.rassoc(@member.education).at(0) %>

其中rassoc用于查找store对应的display,返回[display, store]数组,最后用at(0)返回display提供给页面显示。

[i]有一个问题我弄不明白,第一次调用Dicionary.find_dictionary时,第一个组合的第一个元素是nil,即[[nil, "store1"],["display2", "store2"],...],然后以后就再也没有问题了,这是为什么呢?[/i]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值