1

I am trying to migrate an application to rails 4 and ruby2.

In my model Product, I had this :

attr_accessor :name, :age, :price

which I switched to :

attr_reader :name, :age, :price

In my view I have this :

  %td.small
    = number_with_precision(@p.get_last_usd_price.to_f, precision: 2, delimiter: ",", strip_insignificant_zeros: true)

Everything worked fine with rails 3.2 and attr_accessor. But now I have an issue in get_last_usd_price :

  def get_last_usd_price
    price = 0.0
    puts "--------------------"
    puts self.inspect          #---> prints a #<product> with all the correct attributes
    puts
    puts self.name.inspect     #---> prints nil
    puts @name.inspect         #---> prints nil
    puts "--------------------"
    # blah blah
  end

Basically, all the variables are nil when I try to access them but they are correctly saved into the object instance.

What am I doing wrong? How can I fix this?

Thanks in advance.

Edit : The controller

  def detail_product
    @p = Product.find(params[:product_id]) if params[:product_id].present?
    if !@p.present? then
      flash[:error] = 'No product id'
      redirect_to  :action => :products
    end
  end
Zippie
  • 6,018
  • 6
  • 31
  • 46
Pol0nium
  • 1,346
  • 4
  • 15
  • 31

1 Answers1

8

Remove the attr_readers/attr_accessors if the attributes :name, :age, and :price are saved in the database, since Rails defines those methods already.

For more check this answer: https://stackoverflow.com/a/14452353/1279707

Community
  • 1
  • 1
Zippie
  • 6,018
  • 6
  • 31
  • 46