users enter results only once
I have this script in my results controller:
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_p开发者_如何学JAVAath #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
result is a model. I need the users to input new results when the DistributionSheet is 'open' ONLY ONCE. The elsif above doesnt seem to work. Any advice?
Here is where the @result was referenced:
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
A couple of things. By doing this:
distribution_sheet = DistributionSheet.find(:all, :conditions => ["lifecycle_state = ?","open"]).last
You're loading the every single DistributionSheet
object in your database that meets those conditions. It may seem quick now, but when you've got a ton of records it will take a while. Best to do this instead:
distribution_sheet = DistributionSheet.first(:conditions => "lifecycle_state = 'open'", :order => "id DESC")
That'll accomplish the same goal but won't load the entire association first of all, just the one record you need.
Secondly, perhaps rather than checking @result.size > 1
you should be checking it on the association instead:
distribution_sheet.results.count > 1
This will do an SQL query to count the number of results
for a distribution_sheet
object. You need to have a has_many :results
in the DistributionSheet
model first.
So a couple more things: I would recommend reading the Getting Started guide as well as the Association Basics guide to learn the basics you need in order to solve this problem correctly.
精彩评论