2008-05-28

Rails的表单helper: select

关键字: rails form select
rails的actionviews提供了友好的form builder类来简洁的动态生成表单元素,相比于简单的textfield,select helper有一些特别,传入参数较多,根据rails的api文档,对select的使用说明如下:

引用

select(object, method, choices, options = {}, html_options = {})


object是指select选项所修饰的目标对象,method是目标对象的属性(方法)名, choices是一个数组,包含了选择项的‘name-value’值,options和html_options是选项。以person为例,person有性别gender属性,选项有[['男',0],['女',1]],用select来生成select元素的写法为:

<%=select :person,:gender,[['男',0],['女',1]], {:include_blank=>true,:selected=>0}%>


将生成
<select name="person[gender]">
<option value=""></option>
<option value="0" selected="selected">男</option>
<option value="1">女</option>
</select>


:include_blank=>true表示生成一项空选项。

在线的rails API文档在编程时非常有用,查找方便,位置在

http://www.railsapi.org:8100/
评论
seemoon 2008-06-21
rails提供了不在form_for下的select标签helper 'select_tag',这个select_tag方法的使用颇有不同:

<%=select_tag :sth_id, options_for_select(@groups,selected), {:onchange=>"doSth();"}%>


通过另一个方法options_for_select来生成select的option元素,实现方式比较怪异,不清楚为什么不做得像form_for里的select方法,这样一致性会好很多。
1piece 2008-05-29
seemoon 写道
补充一下,如果选项数据从数据库中获取,通过调用查询返回数组的collect方法可以快捷组装成符合select要求的选项数据,比如以省份表provinces的数据为例

class Province < ActiveRecord::Base
def self.list_options
find(:all, :select=>"id,name", :order=>"name").collect{|p| [p.name,p.id]}
end
end

Province.list_options 返回[['四川',1],['浙江',2],...]

这里的select感觉只是个叠代器一样功能的,和之前的select :name,optipns 不一样吧?要是可是直接生成下拉菜单倒是很方便啊
seemoon 2008-05-29
补充一下,如果选项数据从数据库中获取,通过调用查询返回数组的collect方法可以快捷组装成符合select要求的选项数据,比如以省份表provinces的数据为例

class Province < ActiveRecord::Base
def self.list_options
find(:all, :select=>"id,name", :order=>"name").collect{|p| [p.name,p.id]}
end
end

Province.list_options 返回[['四川',1],['浙江',2],...]
xuchunming 2008-05-28
另外还有 options_from_collection_for_select
和 option_group_form_selection_for_select
也很强大 不过option_group_form_collection_for_selelct 只支持两级 多级就不支持了
发表评论

提醒: 该博客已发表在公共论坛,博客所有留言会成为论坛回贴,留言请注意遵守论坛发贴规则

您还没有登录,请登录后发表评论

seemoon
搜索本博客
最近加入圈子
存档
最新评论