我正在尝试将应用程序迁移到 Rails 4 和 ruby2。
在我的模型 Product
中,我有这个:
attr_accessor :name, :age, :price
我切换到:
attr_reader :name, :age, :price
在我看来我有这个:
%td.small
= number_with_precision(@p.get_last_usd_price.to_f, precision: 2, delimiter: ",", strip_insignificant_zeros: true)
Rails 3.2 和 attr_accessor
一切正常。但是现在我在 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
基本上,当我尝试访问所有变量时,它们都是 nil,但它们已正确保存到对象实例中。
我做错了什么?我该如何解决这个问题?
提前致谢。
编辑: 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
最佳答案
删除 attr_readers
/attr_accessors
如果属性 :name
、:age
和 : price
保存在数据库中,因为 Rails 已经定义了这些方法。
有关更多信息,请查看此答案:https://stackoverflow.com/a/14452353/1279707
关于ruby-on-rails - attr_accessor 和 attr_reader 在 Rails 4 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20195046/