0

我正在用 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
4

1 回答 1

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
于 2012-11-12T00:13:50.447 回答