今天在写程序的时候,需要用到select表单,之前的表单里面的内容都是固定的。用到的都是
<%=select :person,:gender,[['男',0],['女',1]], {:include_blank=>true,:selected=>0}%>
这种方法。
select的api为select(object, method, choices, options = {}, html_options = {})
object是指select选项所修饰的目标对象,method是目标对象的属性(方法)名, choices是一个数组,包含了选择项的‘name-value’值,options和html_options是选项。以person为例,person有性别gender属性,选项有[['男',0],['女',1]],用select来生成select元素的写法为:
Select Menu
select "post",
"person_id",
Person.find_all.collect {|p| [ p.name, p.id ] },
{ :include_blank => true }
相当于html
<select name="post[person_id]">
<option></option>
<option value="1" selected="selected">David</option>
<option value="2">Sam</option>
<option value="3">Tobias</option>
</select>
如今要用到从数据库里面提取值,需通过调用查询返回数组的collect方法可以快捷组装成符合select要求的选项数据,比如以读者类型表reader_roles的数据为例
class ReaderRole < ActiveRecord::Base
def self.list_options
find(:all, :select=>"id,role_name",rder=>"role_name").collect{|r| [r.role_name,p.id]}
end
end
ReaderRole.list_options 来返回[['学生',1],['老师',2],...]
则在视图里面写 <%=f.select(:reader_role_id,ReaderRole.list_options, {:prompt => "请选择一种类型"})%>