rails select 二级联动

Ruby on Rails 编程之select二级联动简例


功能:

点击select下拉菜单,选中某一option, 页面中的text随着更新

要点:

1. select的简例
2. 如何控制selected 即按条件显示指定的option
3. 如何根据select结果刷新页面

1 select 的语法: 如何控制selected 即按条件显示指定的option 关于如何选中某一特定的option,在参考1中有这样的描述

最基本的选择列表框用select helper方法来创立。

form.select(:attribute, choices, options, html_options)

choices的参数讲出现在选择列表框中,参数可以是任何可列举的对象(像数组,hashes, 并且从数据库中查找出来的数据也是允许的).

最简单的选择表但是字符串数组,每一个字符串变成了下拉列表的选项,而且如果其中的一个和a@variable.attribute想匹配的话,他将被选中。

form.select(:attribute, choices, options, html_options)

简例:


<% form_for( :forminfo, :url =>'/my_test' ) do |f| %>
<p>Book Name:</p>
<p>
<%= f.select(:id, @bookslist.map{|c| [c.name, c.id]} ) %>
</p>
<p>
<%= f.collection_select(:id, @bookslist, :id, :name)%>
</p>
<% end %>


注意:
上面的代码包含了 select 和 collection_select。



2

根据上述信息,只要匹配了@variable.attribute的那一条option就会被selected.

controller类似于这样:


@bookslist = Book.find(:all, : order => "id ASC", :select=>"id,name,author")
@forminfo = Book.new()
@forminfo.id = 2

注意: forminfo 就是参考1描述中的@variable.attribute的variable,而f.select(:id, ....) 的id就是attribute. 所以很简单,要想匹配某一条option,只要在controller中设定@forminfo.id。

3 如何根据select结果刷新页面

简单的原理: 根据select的onchange事件,得到当前选中的id,返回到后台根据这个id得到相应的数据,再刷新页面

代码如下:

selectdemo.rhtml


<% form_for( :forminfo, :url =>'/my_test') do |f| %>
<p>Book Name:</p>
<p>
<%= f.select(:id, @bookslist.map{|c| [c.name, c.id]},
{ :include_blank => false },
{:onchange => remote_function(
:update => 'author',
:method => 'get',
:with => "'id='+value",
:url=> {:action=> 'selectdemo' }
)}
)
%>
</p>
<span id="author">

<%= @forminfo.author %>

</span>
<% end %>

my_test_controller.rb


def selectdemo
@bookslist = Book.find(:all, : order =&gt; &quot;id ASC&quot;)

if params!=nil &amp;&amp; params[:id]
@forminfo = Book.find(:first,
:conditions =&gt; [&quot;id = ?&quot;, params[:id]]
)
if @forminfo.author
render_text @forminfo.author
else
render_text &quot;Author Unknown&quot;
end
else
@forminfo = @bookslist.first()
end
end

http://ansondrew.bokee.com/6540554.htm
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值