user2122528
user2122528

Reputation: 71

How do i append some value to an instance variable in ruby on rails?

Here's what I am trying to do in my home controller:

def view
    @product= Product.find(params[:id])
    rand_price = rand(202- @product.price.to_i) + @product.price.to_i
    old_price = rand_price + @product.price.to_i

    @product << old_price  #error line
end

I want to add one more value of old_price to my variable without adding a column for the same in the Product model. The error is:

undefined method `<<' for #<Product:0x7f1362cc5b88>

Upvotes: 4

Views: 3636

Answers (3)

Richard Brown
Richard Brown

Reputation: 11436

You can say

class << @product
  attr_accessor :old_price
end
@product.old_price = old_price

which injects an attribute into the instance variable.

<< the way you are referring to it adds a value to an array, which is not what you're looking to do.

An alternative would be to add:

attr_accessor :old_price

to your Product model. That would add old_price to all instances of Product without it being a field in the table.

Upvotes: 1

user2301496
user2301496

Reputation: 21


Use serializers In model:

class Product << ActiveRecord::Base
  serialize :prices, Array

  ...
end

Column products.prices in database should be string.

And in controller

def update
  @product= Product.find(params[:id])
  rand_price = rand(202- @product.price.to_i) + @product.price.to_i
  new_price = rand_price + @product.price.to_i

  @product.prices << new_price
  @product.save!
end

And you may use it:

  @product.prices # => array of all prices.
  @product.prices.last # => current price

Upvotes: 2

Kiattisak Anoochitarom
Kiattisak Anoochitarom

Reputation: 2157

Error, because @product is Product object not Array.

<< use with Array object

and Ruby has not permission to add property by this way (like Javascript).

You should declare an attr_accessor of 'old_price'

Upvotes: 0

Related Questions