简体   繁体   中英

Adding a counter to controller. Rails 4

I have a rails 4 app. In the controller, I iterate through each assignment entry in the database to check if a requirement is associated with more than one assignment. However, I can't figure out how to add a counter, ie hit = 0, hit = 1, etc. to the controller.

EDIT: The relationship between assignment and requirement is HABTM.

My code is below:

def check_requirements
 @assignments = Assignment.all
 @assignment = Assignment.find(params[:id])
 @requirement = Requirement.find(params[:requirement_id])
 @assignments.each do |assignment|
      if assignment.include(requirement)
        #here's where the counter should go
      end
  end
  if counter is greater than zero or one, do nothing
  else @assignment.delete(requirement)
end

You can use Enumerable#each_with_index

def check_requirements
 @assignments = Assignment.all
 @assignment = Assignment.find(params[:id])
 @requirement = Requirement.find(params[:requirement_id])
 @assignments.each_with_index do |assignment,hit|
      if assignment.include(requirement)
        p "hit : #{hit}"
      end
  end
  if counter is greater than zero or one, do nothing
  else @assignment.delete(requirement)
end
def check_requirements
 @assignments = Assignment.all
 @assignment = Assignment.find(params[:id])
 @requirement = Requirement.find(params[:requirement_id])
 counter = 0
 @assignments.each do |assignment|
      if assignment.include(requirement)
        counter+=1
      end
  end
  if counter is greater than zero or one, do nothing
  else @assignment.delete(requirement)
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM