Rails模型中的实例变量 [英] Instance Variables in Rails Model

查看:66
本文介绍了Rails模型中的实例变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的Rails模型中初始化一个实例变量,该实例变量将保存一个数组,并且我想在模型中的其他方法中访问此变量.我试过了:

I want to initialize an instance variable within my Rails model that will hold an array and I want to access this variable in other methods within my model. I tried this:

class Participant < ActiveRecord::Base

  @possible_statuses = [
    'exists',
    'paired',
    'quiz_finished',
    'quiz_results_seen',
    'money_sent'
  ]

  def statuses
    @possible_statuses
  end

但是当我尝试使用Rails控制台进行以下操作时:

But when I tried the following using rails console:

 Participant.first.statuses

我归零了:(

为什么会这样? 有什么方法可以完成我要完成的工作?

Why does this happen? Is there a way to accomplish what I am trying to accomplish?

推荐答案

对我来说,最好的答案是创建一个类变量,而不是实例变量:

The best answer for me was to create a class variable, not an instance variable:

@@possible_statuses = [
    'exists',
    'paired',
    'chat1_ready',
    'chat1_complete'
]

然后我可以在类的方法中自由访问它:

I could then freely access it in methods of the class:

  def status=(new_status)
    self.status_data = @@possible_statuses.index(new_status)
  end

这篇关于Rails模型中的实例变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆