我的开发环境:
以下是代表问题的程序流程的一部分。
请求来了:
#action
def create
begin
@report = Report.new(params[:report])
...
rescue LocationNotFound => e
...
end
end
报告构造函数:
class Report
attr_accessor :locations
def initialize(params = {})
@locations = params[:locations] ? fetch_locations(params[:locations]) : []
end
...
end
fetch_locations:
def fetch_locations(loc_names)
Rails.logger.debug "LOC_NAMES: " + loc_names.inspect
ls = Location.find(:all, :conditions => [ # line 57
"locations.name in (#{loc_names.map{'?'}.join(',')})",
*loc_names
], :include => [:sample_summaries, :samples]) # loc_names will never be empty
...
end
位置模型:
class Location < ActiveRecord::Base
has_many :sample_summaries
has_many :samples, :through => :sample_summaries
...
end
现在,第一次(在乘客重新启动后)这个运行正常并完成工作。在大多数情况下,我都会收到错误:
Mar-11 11:01:00 #15098 DEBUG: LOC_NAMES: ["Moscow, RF", "London, UK"]
Mar-11 11:01:00 #15098 DEBUG: Location Load (0.0ms) SELECT * FROM `locations` WHERE (locations.name in ('Moscow, RF','London, UK'))
Mar-11 11:01:00 #15098 DEBUG: SampleSummary Load (0.0ms) SELECT `sample_summaries`.* FROM `sample_summaries` WHERE (`sample_summaries`.location_id IN (1,3))
Mar-11 11:01:00 #15098 DEBUG: SampleSummary Columns (0.0ms) SHOW FIELDS FROM `sample_summaries`
Mar-11 11:01:00 #15098 FATAL:
NoMethodError (You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.include?):
app/models/report.rb:57:in `fetch_locations'
app/models/report.rb:9:in `initialize'
app/controllers/report_controller.rb:11:in `new'
app/controllers/report_controller.rb:11:in `create'
对我来说很随意。有什么想法吗?
P.S。我还尝试将查询包装在uncached
块中,但这并未改变任何内容。
修改
以下是SampleSummary模型的样子:
class SampleSummary < ActiveRecord::Base
has_many :samples
belongs_to :location
... #validations
default_scope :include => :samples, :order => 'rss_ts desc'
...
end
EDIT2
它在控制台中不会失败。
答案 0 :(得分:0)
那么,如果你通过./script/console(控制器动作的相关部分)多次使用相同的参数运行它,它会随机失败?或者它一直都失败了?目前尚不清楚。
随便,为什么不试试......
ls = Location.find(:全部, :conditions =&gt; [“(。)中的locations.name”,loc_names], :include =&gt; :sample_summaries =&gt; {:samples})
答案 1 :(得分:0)
由于sample_summaries的默认范围包括样本,您可以尝试:
def fetch_locations(loc_names)
ls = Location.find(:all,
:conditions => {:locations => {:name => loc_names},
:include => :sample_summaries
)
end
另外,如果你完全离开:include off,它会失败吗?
答案 2 :(得分:0)
这就是它发生的事情:
好消息是,它只发生在开发模式(config.cache_classes = false
)。将其更改为true
将使其消失(代价是每次更改后都不会忘记重新启动服务器)。