我正在编写一个带有switch case的循环,而不是三次查询数据库,我在一个查询中获得所有查找并循环使用条件来分配给不同的实例变量(我将以简单的形式用作集合)。我不确定如何将活动记录关系附加到实例变量,请帮助我。
class QuestionsController < ApplicationController
def index
@question = Question.new
@question_lookups = Lookup.where({:look_up_for => "question"})
@question_lookups.each do |lk|
case lk.look_up_type
when 'mode'
@question_mode = lk #How can i do this here..?
when 'status'
@question_status = lk
else
@question_type = lk
end
end
session[:lk] = @question_mode
# @question_mode = Lookup.where({:look_up_for => "question", :look_up_type => "mode"})
# @question_status = Lookup.where({:look_up_for => "question", :look_up_type => "status"})
# @question_type = Lookup.where({:look_up_for => "question", :look_up_type => "type"})
end
end
答案 0 :(得分:1)
将question_mode等转换为数组并将lk推送到它
@question_mode, @question_status, @question_type = []
@question_lookups.each do |lk|
case lk.look_up_type
when 'mode'
@question_mode << lk #How can i do this here..?
when 'status'
@question_status << lk
else
@question_type << lk
end
end