免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2210 | 回复: 3
打印 上一主题 下一主题

让查询变得更优雅 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2011-09-22 15:40 |只看该作者 |倒序浏览
让查询变得更优雅



RailsWhere可以让代码变得更简洁。



看一下插件的自述文件。



Ruby代码

  1. === Returning SQL

  2. sql = Where.new('x=?',5).and( Where.new('x=?',6).or('x=?',7)).to_s
  3. # returns (x=5) and ( (x=6) or (x=7) )

  4. === Building a complicated where clause made easy

  5. def get_search_query_string
  6.    where = Where.new
  7.    where.and('users.first_name like ?', params[:search_first_name] + '%') unless params[:search_first_name].blank?
  8.    where.and('users.last_name like ?', params[:search_last_name] + '%') unless params[:search_last_name].blank?

  9.    status_where = Where.new
  10.    for status in params[search_statuses].split(',')
  11.      status_where.or 'status=?', status
  12.    end
  13.    where.and status_where unless status_where.blank?

  14.    where.to_s
  15. end

  16. User.find(:all, :conditions => get_search_query_string)

  17. === Inline

  18. User.find(:all, :conditions => Where.new('first_name like ?', 'Tim').and('last_name like ?', 'Harper'))
复制代码
Rails2.2.2下可以直接运行,Rails2.3.4的话,需要进行小小的改动:


Ruby代码

  1. # RAILS_ROOT/vendor/railswhere/lib/where.rb

  2. # 2.2.2
  3. @criteria = ActiveRecord::Base.send(:sanitize_sql_array, criteria)

  4. # 2.3.4
  5. @criteria = ActiveRecord::Base.send(:sanitize_sql_array, criteria, nil)
复制代码

论坛徽章:
0
2 [报告]
发表于 2011-09-22 20:46 |只看该作者
Rails发展更新得太快,3.0/3.1的变化还是比较大。

论坛徽章:
46
15-16赛季CBA联赛之四川
日期:2018-03-27 11:59:132015年亚洲杯之沙特阿拉伯
日期:2015-04-11 17:31:45天蝎座
日期:2015-03-25 16:56:49双鱼座
日期:2015-03-25 16:56:30摩羯座
日期:2015-03-25 16:56:09巳蛇
日期:2015-03-25 16:55:30卯兔
日期:2015-03-25 16:54:29子鼠
日期:2015-03-25 16:53:59申猴
日期:2015-03-25 16:53:29寅虎
日期:2015-03-25 16:52:29羊年新春福章
日期:2015-03-25 16:51:212015亚冠之布里斯班狮吼
日期:2015-07-13 10:44:56
3 [报告]
发表于 2011-09-23 10:10 |只看该作者
一点也不优雅,过度包装

论坛徽章:
0
4 [报告]
发表于 2011-09-23 12:30 |只看该作者
功能的累加,必然导致复杂度和过度包装。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP