加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 从ActiveRecord查询返回类型

发布时间:2020-12-17 02:17:48 所属栏目:百科 来源:网络整理
导读:如果我要从ActiveRecord调用中获取Relation,Array或其他类型,我会告诉我什么?我知道我可以在控制台中键入.class并弄明白,但是调用本身有什么能让我知道我要的是什么吗? 解决方法 你知道,Rails有时会对你说谎 – 所有魔术师都会这样做:) Rails允许您通过链
如果我要从ActiveRecord调用中获取Relation,Array或其他类型,我会告诉我什么?我知道我可以在控制台中键入.class并弄明白,但是调用本身有什么能让我知道我要的是什么吗?

解决方法

你知道,Rails有时会对你说谎 – 所有魔术师都会这样做:)

Rails允许您通过链接has_many关联来构建复杂查询.此功能的核心是一堆XXXAssocation(如HasManyAssociation)类.
当您在has_many关联上调用.class时,您的调用实际上适用于HasManyAssociation实例.但这是神奇的开始:

# collection_proxy.rb
instance_methods.each { |m| undef_method m unless m.to_s =~ /^(?:nil?|send|object_id|to_a)$|^__|^respond_to|proxy_/ }

Rails HasManyAssociation实例的undefs(隐藏)方法(除了少数,正如你在正则表达式中看到的那样)然后使用delegation和method_missing将你的调用传递给一些底层数组(如果你试图获取记录)或者关联本身(如果你链接你的协会):

delegate :group,:order,:limit,:joins,:where,:preload,:eager_load,:includes,:from,:lock,:readonly,:having,:pluck,:to => :scoped 

  delegate :target,:load_target,:loaded?,:to => :@association

  delegate :select,:find,:first,:last,:build,:create,:create!,:concat,:replace,:delete_all,:destroy_all,:delete,:destroy,:uniq,:sum,:count,:size,:length,:empty?,:any?,:many?,:include?,:to => :@association

  def method_missing(method,*args,&block)
    match = DynamicFinderMatch.match(method)
    if match && match.instantiator?
      send(:find_or_instantiator_by_attributes,match,match.attribute_names,*args) do |r|
        proxy_association.send :set_owner_attributes,r
        proxy_association.send :add_to_target,r
        yield(r) if block_given?
      end
    end

    if target.respond_to?(method) || (!proxy_association.klass.respond_to?(method) && Class.respond_to?(method))
      if load_target
        if target.respond_to?(method)
          target.send(method,&block)
        else
          begin
            super
          rescue NoMethodError => e
            raise e,e.message.sub(/ for #<.*$/," via proxy for #{target}")
          end
        end
      end

    else
      scoped.readonly(nil).send(method,&block)
    end
  end

因此,HasManyAssociation实例决定自己要处理什么以及需要通过隐藏数组完成什么(类方法不是HasManyAssociation所感兴趣的,所以它将在这个隐藏数组上调用.结果当然是Array,有点欺骗).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读