Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/67.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何在RubyonRails中向实例变量附加一些值?_Ruby On Rails_Ruby_Ruby On Rails 3_Controller_Instance Variables - Fatal编程技术网

Ruby on rails 如何在RubyonRails中向实例变量附加一些值?

Ruby on rails 如何在RubyonRails中向实例变量附加一些值?,ruby-on-rails,ruby,ruby-on-rails-3,controller,instance-variables,Ruby On Rails,Ruby,Ruby On Rails 3,Controller,Instance Variables,以下是我在家用控制器中尝试执行的操作: 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 你可以说 class

以下是我在家用控制器中尝试执行的操作:

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
你可以说

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

class错误,因为@product是产品对象而不是数组


使用序列化程序 在模型中:

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

  ...
end

谢谢,但是我应该把这个类放在哪里?在这样做之后,我还可以制作@product,一个产品模型对象吗?你可以把它放在你想要访问
旧的\u price
属性之前的任何地方。它不是一个单独的类,它正在修改
@old\u price
的类。我为答案添加了一个更简单的替代方案。不知道为什么有人会给这个答案打-1。对于想要好的、干净的、经过重新分解的代码来说,这是一个合理的问题。
class Product << ActiveRecord::Base
  serialize :prices, Array

  ...
end
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
  @product.prices # => array of all prices.
  @product.prices.last # => current price