Ser*_*ora 0 sqlite postgresql ruby-on-rails ruby-on-rails-3
我试图将给定的Header字段与Alarm模型中的其他字段进行比较.正如您在代码中看到的,我在3个不同的步骤中过滤警报.前2个工作完美.但是,最后一个不起作用.它说:
undefined method `where' for #<Array:...
Run Code Online (Sandbox Code Playgroud)
据我所知,.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
Run Code Online (Sandbox Code Playgroud)
任何帮助发现我错过的东西非常感谢.谢谢
在第一行中,您成功返回了一个ActiveRecordRelation对象@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])
Run Code Online (Sandbox Code Playgroud)
此时,您可以应用其他.where(...)方法,条件或范围,@alarmsT以进一步构建ARel表达式并返回结果.
但是,然后在此关系上运行过滤器,转换@alarmsT为实例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
Run Code Online (Sandbox Code Playgroud)
您无法再构建ARel表达式,因为Array您不了解您的ARel .where(...)方法或任何Alarm模型的范围或属性.这就是为什么在下面的代码中你得到undefined method 'where' for #<Array:...错误 - 你正在调用.where()一个实例Array; 一种不存在的方法.
@alarmsF = []
@header.events.each do |e|
@alarmsF = @alarmsF + @alarmsT.where("alarms.location LIKE ?", e.town)
end
Run Code Online (Sandbox Code Playgroud)
您可以通过不按类别ID进行过滤而使用连接来解决此问题.构建这样的连接(以验证相关表/列中至少存在一个值的子集)在很容易通过谷歌和StackOverflow找到的地方记录.
| 归档时间: |
|
| 查看次数: |
7082 次 |
| 最近记录: |