0

For some weird reason an instance variable I have puts out two different values on two different occasions.

$ puts @project.to_yaml

gives:

  id: 3
  title: '123'
  created_at: 2014-04-07 23:54:18.253262000 Z
  updated_at: 2014-04-09 09:20:33.847246000 Z
  amount_donated: 50000

and

$ @project.amount_donated

gives:

  nil

Explain this one to me because I'm terribly lost.

EDIT Project model

class Project < ActiveRecord::Base
  require 'date'

  attr_accessor(:amount_donated)
  before_save :convert_params

  def convert_params
    if amount_donated.present?
      value = amount_donated.to_s.split(',').join
      value = value.to_f * 100
      update_column(:amount_donated, value.to_i)
    end
  end
end
3
  • 1
    whats is @project? could you please add the Project.rb source code (if it is a model, as I'm guessing) Commented Apr 9, 2014 at 10:07
  • 1
    why there is , at the end of attr_accessor ? Commented Apr 9, 2014 at 10:19
  • copy and paste error there one one thing that was behind it that doesn't matter pdf. i'll remove that from the edit Commented Apr 9, 2014 at 10:20

2 Answers 2

1

update_column(:amount_donated, value.to_i) shows that you have a column amount_donated, but attr_accessor :amount_donated shows that you have a virtual attribute. So which one is it?

I'd suggest removing attr_accessor :amount_donated

edit:

The attr_accessor :amount_donated does something like this:

class Project < ActiveRecord::Base
  require 'date'

  before_save :convert_params

  def amound_donated
    @amount_donated
  end

  def amound_donated=(value)
    @amount_donated = value
  end

  def convert_params
    if amount_donated.present?
      value = amount_donated.to_s.split(',').join
      value = value.to_f * 100
      update_column(:amount_donated, value.to_i)
    end
  end
end

Thus when you accessed @project.amount_donated you were actually accessing the getter method amount_donated not the column (ActiveRecord getter).

Seems that to_yaml saw the column instead of the ActiveRecord's getter.

Sign up to request clarification or add additional context in comments.

1 Comment

attr_accessor creates new getter and setter methods, overwriting AciveRecord's default getters and setters
0

Try this, might be you are using cached copy of @project

@project.reload.amount_donated

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.