Instance Variables in Rails Model

断了今生、忘了曾经 提交于 2019-12-12 08:12:34

问题


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

But when I tried the following using rails console:

 Participant.first.statuses

I am returned nil :(

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


回答1:


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




回答2:


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



回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/11252940/instance-variables-in-rails-model

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