rails find 函数

情况:想以参数的形式传入Model的find函数,
如args ={ :limit => 10 },执行Model.find(:all,args,:join=>"...")时,传入的参数没作用.(:join是固定的)

分析:
源码:

def find(*args)
options = args.extract_options!
validate_find_options(options)
set_readonly_option!(options)

case args.first
when :first then find_initial(options)
when :last then find_last(options)
when :all then find_every(options)
else find_from_ids(args, options)
end
end

说明:
(1)extract_options!函数会从args中筛选出是hash的参数
如:

extract_options!(1,2,:a => :b) => {:a=>:b}
extract_options!({:a=>:b},:b=>:c) => {:b=>:c}

(2)validate_find_options将检测options中是否包含错误的参数.
源码:

VALID_FIND_OPTIONS = [ :conditions, :include, :joins, :limit, :offset,
:order, :select, :readonly, :group, :from, :lock ]
def validate_find_options(options) #:nodoc:
options.assert_valid_keys(VALID_FIND_OPTIONS)
end

说明:当options包含非法参数时,assert_valid_keys建抛出异常
(3)从代码可以看出find的第一个参数一定要是first,last,all

结论:
当find函数调用extract_options!时,传入的参数为({:limit=>10},:join=>".."),
返回的值为{:join=>".."},而:limit=>10被过滤掉了,所以没有返回10条记录.

注意:
正确:find(:all,:limit=>10 ,:joins =>".(省略).", :conditions => [" fe.event_id = ? " , event.id])
出错:find(:all,:joins =>".(省略).", :conditions => [" fe.event_id = ? " , event.id], :limit=>10 )
不知:limit放在:conditions后为什么会出现语法错误?
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值