0

我正在尝试将给定字段与模型Header中的其他字段进行比较。Alarm正如您在代码中看到的,我通过 3 个不同的步骤过滤警报。前 2 个工作完美。但是,最后一个不起作用。它说:

undefined method `where' for #<Array:...

据我了解.where是一种适用于数组的类方法。为什么在这里不起作用?我也尝试过.find_all_by不同的东西......但无济于事。

@header = Header.find(1)

# Extracts those alarms that are ACTIVE and have something in common with the tittles
@alarmsT = Alarm.activated.where("keyword in (?)", [@header.title_es, @header.title_en, @header.title_en])

# Extracts alarms when Header has at least the same categories as an alarm
@alarmsT = @alarmsT.select do |alarm| 
   @header.category_ids.all?{|c| alarm.category_ids.include? c }
end

// this is the one that does NOT work
# Extract alarms which share the same location as Header.events' town
@alarmsF = [] 
@header.events.each do |e|
    @alarmsF =  @alarmsF + @alarmsT.where("alarms.location LIKE ?", e.town)
end

任何帮助发现我所缺少的东西都非常感谢。谢谢


在查询中将 getdate() - 7 小时设置为零

我有一个查询,其中我使用日期作为条件 ( paiddate)。

我想要从前 7 天到今天的记录。所以,我的陈述看起来像这样

PaidDate >= GETDATE() - 7

我以为我会像这样回到开始日的 0 小时

PaidDate > DATEADD(d,DATEDIFF(d,7,getdate()),0)

但是,我收到一条错误消息:

varchar 值 '2224560081' 的转换溢出了一个 int 列

知道为什么会发生这种情况以及如何解决吗?

4

2 回答 2

7

In your first line, you're successfully returning an ActiveRecordRelation object in @alarmsT

# Extracts those alarms that are ACTIVE and have something in common with the tittles
@alarmsT = Alarm.activated.where("keyword in (?)", [@header.title_es, @header.title_en, @header.title_en])

At this point you could apply additional .where(...) methods, conditions or scopes on @alarmsT to further build up the ARel expression and the results returned.

However, you then run a filter over this relation, converting @alarmsT to an instance of Array

# Extracts alarms when Header has at least the same categories as an alarm
@alarmsT = @alarmsT.select do |alarm| 
   @header.category_ids.all?{|c| alarm.category_ids.include? c }
end

You can no longer build up the ARel expression, since Array doesn't know about your ARel's .where(...) method, or any of your Alarm model's scopes or attributes. This is why in the code below you're getting the undefined method 'where' for #<Array:... error -- you're calling .where() on an instance of Array; a method that does not exist.

@alarmsF = [] 
@header.events.each do |e|
  @alarmsF =  @alarmsF + @alarmsT.where("alarms.location LIKE ?", e.town)
end

You can fix this by not doing the select to filter by category ids and instead using a join. Building such a join (to verify existence of at least a subset of values in a related table/column) is documented quite a bit on places easily found through google and here on StackOverflow.

于 2013-04-16T16:31:06.720 回答
3

就像@Deefour 所说,select您正在收集数据Array而不是ActiveRecord::Relation对象。

你确定你需要LIKE查询吗?通过查看它,我想您可以进行简单的直接比较。如果我的假设是正确的,您可以重新排列代码的最后一部分:

@alarmsF = []
towns_from_events = @header.events.collect(&:town)

@alarmsT.each do |alarmsT|
    @alarmsF << alarmsT if towns_from_events.include?(alarmsT.location)
end
于 2013-04-16T16:47:12.537 回答