简体   繁体   中英

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>

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.


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

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM