Instance Variables in Rails Model

十年热恋 提交于 2019-12-03 15:45:15

I would recommend using a constant for this kind of cases:

class Participant < ActiveRecord::Base

  STATUSES = [
    'exists',
    'paired',
    'quiz_finished',
    'quiz_results_seen',
    'money_sent'
  ]

If you want to access that array from the inside class, just do STATUSES, and from the outside class use Participant::STATUSES

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

In your example, @possible_statuses is a variable on the class rather than on each instance of the object. Here is a rather verbose example of how you might accomplish this:

class Participant < ActiveRecord::Base

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

  def self.possible_statuses
    @possible_statuses
  end

  def possible_statuses
    self.class.possible_statuses
  end

  def statuses
    possible_statuses
  end

end

As mentioned in other answers, if that list of statuses never changes, you should use a constant rather than a variable.

The instance variable will only exist when you create the model, since it is not being stored in a database anywhere. You will want to make it a constant as per Nobita's suggestion. Alternatively, you could make it a module like...

module Status
  EXISTS = "exists"
  PAIRED = "paired"
  QUIZ_FINISHED = "quiz_finished"
  QUIZ_RESULTS_SEEN = "quiz_results_seen"
  MONEY_SENT = "money_sent"

  def self.all
    [EXISTS, PAIRED, QUIZ_FINISHED, QUIZ_RESULTS_SEEN, MONEY_SENT]
  end
end

This gives you a bit more control and flexibility, IMO. You would include this code nested in your model.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!