在Ruby / Rails中调用数组上的数组

时间:2015-08-28 15:17:22

标签: arrays ruby ruby-on-rails-4 hash

我在rails 4.0.x中有一个相当复杂的应用程序,所以我不太深入了解逻辑,但会解释我遇到的问题。

我有一个权证模型,我写了一个类方法来替换像这样的简单范围。它使用套管来代替权证类型,并向我显示所有被认为是有效和开放的权证。

  def self.active_and_open
    find_by_sql("
    select id, case warn_type when 'FT' then 'AW' when 'WI' then 'AW' when 'VP' then 'AW' when 'AW' then 'AW' when 'CP' then 'CP' when 'CW' then 'CP' end as warn_type, warn_date_issued, warn_status, warnv_citation_no, warnv_viol_no warnv_name_code, created_at, updated_at, last_seen_at, citation_id, person_id,warn_docket_no, warn_closed_date, warn_rid, violation_id, total, rank, changed_by, collection_fee, collection_amount, exclude_from_collection, open_coll_at from warrants WHERE (warn_closed_date is null and warn_status = '')
     ")
  end

然后我在我的人模型中有一个方法(Person有很多权证关联),方法是在Person对象上调用权证显示active_and_open权证并按warn_typewarn_closed_date分组

   def open_warrant_types
    warrants.active_and_open.group(:warn_type, :warn_closed_date).count(:warn_type)
  end

然后在我的帮助者中,我称之为这样的方法并尝试对权证进行分组,首先根据权证类型进行转换,然后显示一个计数,即1 bondable 1 non bondable name是人物对象I&#39 ;传球

 def open_warrants_types_and_counts(name)
 ( name.open_warrant_types2.collect{ |wt| "#{wt.last}  #{translate_warrant_type(Warrant::WARRANT_TYPE[(wt.first.kind_of?(Array) ? wt.first.first : wt.first)])}" }.join(', ') )
  end

我遇到的问题是此类方法self.active_and_open创建了一个数组,而open_warrant_types我得到了undefined method group for array。我的旧范围或active_and_open返回了一个哈希,下面的范围是:

scope :active_and_open, -> {where("warn_closed_date is null and warn_status <> 'I'")}

传递给open_warrant_types中的.group方法时,此哈希工作正常,但我不确定如何使用数组具有相同的功能。我从未使用.group方法.group_by而且API文档没有告诉我关于如何在数组上调用.group需要了解的内容。< / p>

我意识到这段代码可能非常复杂,所以我可以接受重构和建议,但是现在我只想弄清楚如何在数组上调用.group或转换数组到持久化k,v的哈希中,所以我可以使用现有的方法。

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

你可以做s.th.就像Warrant.select('warrants.*, case warn_type when 'FT' then 'AW' when 'WI' then 'AW' when 'VP' then 'AW' when 'AW' then 'AW' when 'CP' then 'CP' when 'CW' then 'CP' end as warn_type')那样,你得到一个ActiveRecord表达式,你可以调用常见的嫌疑人。

但我强烈建议尽可能地将本机SQL从您的应用程序中删除,并在应用程序中使用SQL进行翻译。

即。制作一个哈希来翻译你的warn_types:

WT_HASH = {
'FT' => 'AW',
'VP' then 'AW',
..
}

创建方法

class Warrant

def translated_warn_type
  WT_HASH[self.warn_type]
end
..