我有一个rails 4 app。在控制器中,我遍历数据库中的每个赋值条目,以检查需求是否与多个赋值相关联。但是,我无法弄清楚如何向控制器添加计数器,即hit = 0,hit = 1等。
编辑:分配和要求之间的关系是HABTM。
我的代码如下:
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
答案 0 :(得分:2)
您可以使用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
答案 1 :(得分:1)
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