haohong0322
haohong0322
2011-10-10 08:55
浏览 249
已采纳

在rails里面写mysql语句问题

quarterIdThe = params[:quarterThe_id].to_s #得到--本季度操作--对话框

department = params[:department_id] #得到选择的部门名称
upThe,downThe = getUpTheDownThe(quarterIdThe) #这是我自己写的一个方法,没有错误
busiesses = Business.find_by_sql["SELECT d.name FROM businesses AS b
JOIN employees AS e ON (b.employee_id = e.id)
JOIN departments AS d ON (e.department_id = d.id)
WHERE d.code = Department AND b.out_date <= UpThe AND b.out_date > DownThe ",{:Department => 'department',:UpThe=> 'upThe',:DownThe=> 'downThe'}]
我用的rails,这是在控制里面写的代码,主要是find_by_sql后边的代码有问题,总是提示说参数个数错误,求各位帮忙解决,或者是在model中写这个方法的话代码应该怎样写

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • horace_lee
    horace_lee 2011-10-11 18:58
    已采纳

    [code="sql"]
    Business.find_by_sql["SELECT d.name FROM businesses AS b
    JOIN employees AS e ON (b.employee_id = e.id)
    JOIN departments AS d ON (e.department_id = d.id)
    WHERE d.code = ? AND b.out_date <= ? AND b.out_date > ?", department, upThe, downThe]

    [/code]

    点赞 评论
  • iteye_18727
    iteye_18727 2011-10-11 15:49

    哇靠。LZ,你的代码应该放在code标签里面哎。看的太费劲了,写负复杂的SQL,一不小心就错了。

    [code="ruby"]

    在model中,定义一些scope(如果是rails3,稍有不同。)
    named_scope :xxx, :condition=>[...],:joins=>...
    named_scope :yyy, :condition=>[...],:joins=>...

    把你的查询条件拆分,或者不能拆分的尽量写成hash,而不是sql字符串。虽然效率会变慢点.....
    然后,在controller中,直接当做一个类方法调用。

    Business.xxx
    Business.xxx.yyy //也可以传参,具体参考API,查一下named_scope就知道具体的用法了,有很详细的例子。

    [/code]

    点赞 评论
  • okela1985851010
    okela1985851010 2011-10-12 12:08

    {:Department => 'department',:UpThe=> 'upThe',:DownThe=> 'downThe'}
    你怎么这样写。。
    api

    You can use the same string replacement techniques as you can with ActiveRecord#find

    Post.find_by_sql ["SELECT title FROM posts WHERE author = ? AND created > ?", author_id, start_date]

    [#"The Cheap Man Buys Twice"}>, ...]

    点赞 评论

相关推荐