Instance Variables in the Rails Model

I want to initialize an instance variable in my Rails model that will contain an array, and I want to access this variable in other methods of 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

But when I tried using the rails console, follow these steps:

 Participant.first.statuses

I'm coming back nil :(

Why is this happening? Is there a way to accomplish what I'm trying to accomplish?

+5
source share
4 answers

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

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

Then I could freely access it in class methods:

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

I would recommend using a constant for such cases:

class Participant < ActiveRecord::Base

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

, STATUSES, Participant::STATUSES

+10

@possible_statuses - , . , :

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

, , , .

+2

, . Nobita. , , ...

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

, . , .

0

All Articles