divideByZero
divideByZero

Reputation: 1188

Ruby on Rails, access to non persistent attribute and attribute default value

I want to build application with survey functionality. To receive answers from users I've added non persistent attribute is_checked (also I have persistent attribute is_right in my schema).

class Answer < ActiveRecord::Base
  belongs_to :question
  attr_accessor :is_checked

  def initialize
    self.is_checked = false
  end

  after_initialize :default_values

  private

  def default_values
    self.is_right ||= false
  end
end

But when I open rails console and run:

Survey.first.questions.last.answers.last.attributes

There is no is_checked attribute. If I call is_checked getter on answer instance I get nil.

Upvotes: 2

Views: 1076

Answers (1)

nathanvda
nathanvda

Reputation: 50057

Imho your initialize method is never called, otherwise, since you do not call super you would loose all active-record initialization.

Your initialize definitely does not match the signature of the original (it accepts at least a hash), but the after_initialize was introduced exactly for this reason.

So I would just extend the default_values to include setting your is_checked.

Also attr_accessor creates access methods to an instance-variable, so just set that instance variable instead.

So I would write

class Answer < ActiveRecord::Base
  belongs_to :question
  attr_accessor :is_checked

  after_initialize :default_values

  private

  def default_values
    self.is_right ||= false
    @is_checked = false 
  end
end

Upvotes: 3

Related Questions