如何将关系对象分配给rails中的实例变量

时间:2012-11-11 22:34:18

标签: ruby-on-rails

我正在编写一个带有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

1 个答案:

答案 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