在Controller中调用方法模型

时间:2013-11-29 03:33:44

标签: ruby-on-rails methods controller

我有以下型号; (APP /模型/ student_inactivation_log.rb)

class StudentInactivationLog < ActiveRecord::Base
    belongs_to :student
    belongs_to :institution_user
    belongs_to :period

    validates_presence_of :student_id, :inactivated_on, :inactivation_reason

    INACTIVATION_REASONS = [{ id: 1, short_name: "HTY", name: "You didn't study enough!"},
                            { id: 2, short_name: "KS", name: "Graduated!"},
                            { id: 3, short_name: "SBK",name: "Other Reason"}]

    Class methods
        class << self
        def inactivation_reason_ids
            INACTIVATION_REASONS.collect{|v| v[:id]}
        end

        def inactivation_reason_names
            INACTIVATION_REASONS.collect{|v| v[:name]}
        end

        def inactivation_reason_name(id)
          INACTIVATION_REASONS.select{|t| t[:id] == id}.first[:name]
        end

        def inactivation_reason_short_name(id)
          INACTIVATION_REASONS.select{|t| t[:id] == id}.first[:short_name]
        end

        def inactivation_reason_id(name)
          INACTIVATION_REASONS.select{|t| t[:name] == name}.first[:id]
        end
    end

    # Instance methods
    def inactivation_reason_name
        self.class.inactivation_reason_name(self.inactivation_reason)
    end

    def inactivation_reason_short_name
        self.class.inactivation_reason_short_name(self.inactivation_reason)
    end

    def inactivation_reason_id
        self.class.inactivation_reason_id(self.inactivation_reason)
    end
end

我想从我的控制器调用这些停用原因,这是app / controllers / student / session_controllers.rb文件:

class Student::SessionsController < ApplicationController
    layout 'session'

    def create
        student = Student.authenticate(params[:student_number], params[:password])
        if student.active
            session[:student_id] = student.id
            redirect_to student_main_path, :notice => 'Welcome!'
        elsif (student and student.student_status == 3) or (student and !student.active)
            flash.now.alert = "You can't login because #REASON_I_AM_TRYING_TO_CALL"
            render 'new'
        else
            ....
    end
end

如果他们无法登录,我想向学生展示他们在系统上的失活原因。

如何从此控制器文件中调用INACTIVATION_REASONS?有可能吗?

提前致谢!

1 个答案:

答案 0 :(得分:2)

这只是一个常数,所以你可以把它称为常数。

StudentInactivationLog::INACTIVATION_REASONS

更新

我实际上意识到你想要的是使用db中保存的原因代码或短名称来表示字符串。

如果是这样,我建议您直接使用短名称作为哈希。对于这种轻微的情况,“id”看起来多余。

INACTIVATION_REASONS = {"HTY"=>"You didn't study enough!",
                        "KS"=>"Graduated!",
                        "SBK"=>"Other Reason"}

validates :inactivation_reason, inclusion: { in: INACTIVATION_REASONS.keys,
  message: "%{value} is not a valid short name" }

def full_reason_message
  INACTIVATION_REASONS[self.inactivation_reason]
end

然后,在控制器中显示原因的完整信息

reason = @student.full_reason_message

这是个主意。我没有检查过你的其他型号代码。您需要将原因保存为短名称而不是id,如果您决定以这种方式使用它,则需要修改/删除某些代码。