我在结果控制器中有这个脚本:
distribution_sheet = DistributionSheet.find(:all, :conditions => ["lifecycle_state = ?","open"]).last
if distribution_sheet.nil?
redirect_to root_path #you could redirect somewhere else if you want
flash[:notice] = "There are currently no active EQAs"
# elsif (@result.size > 1)
# redirect_to root_path #you could redirect somewhere else if you want
# flash[:notice] = "You have already entered your EQA for EQA number #{distribution_sheet.id}"
else
flash[:notice] = "EQA number #{distribution_sheet.id} is open for submissions"
end
结果是一个模型。当DistributionSheet仅“打开”时,我需要用户输入新的结果。上面的elsif似乎没有用。有什么建议吗?
以下是引用@result的地方:
def new
@result = Result.new
distribution_sheet = DistributionSheet.find(:all, :conditions => ["lifecycle_state = ?","open"]).last
@result.distribution_sheet_id = distribution_sheet.id
10.times do
@result.specimen_results.build
end
specimen_ids = distribution_sheet.specimens.collect{|specimen| specimen.id}
@result.specimen_results.each do |specimen_result|
specimen_result.specimen_id = specimen_ids.shift
end
@result.lab_id = current_user.lab_id
end
答案 0 :(得分:0)
有几件事。通过这样做:
distribution_sheet = DistributionSheet.find(:all, :conditions => ["lifecycle_state = ?","open"]).last
您正在加载满足这些条件的数据库中的每个DistributionSheet
对象。现在看起来似乎很快,但是当你有大量的记录时,它需要一段时间。最好这样做:
distribution_sheet = DistributionSheet.first(:conditions => "lifecycle_state = 'open'", :order => "id DESC")
这将实现相同的目标,但不会首先加载整个关联,只需要您需要的一条记录。
其次,也许不是检查@result.size > 1
你应该在关联上检查它:
distribution_sheet.results.count > 1
这将执行SQL查询以计算results
对象的distribution_sheet
个数。您需要先在has_many :results
模型中设置DistributionSheet
。
还有一些事情:我建议您阅读Getting Started guide以及Association Basics guide,以了解正确解决此问题所需的基础知识。