读 Agile Web Development with Rails 笔记(二)

近日照例一步一步看下去。。
遇到第一个问题
用rake db:migrate的时候通不过。。。
我用网上下来的源程序依然通不过。。。

:decimal
#002_add_price.rb

class AddPrice < ActiveRecord::Migration
def self.up
add_column :products, :price, :decimal, :precision => 8, :scale =>
2, :default => 0
end

def self.down
remove_column :products, :price
end
end


出错
[quote]
== CreateProducts: migrating ==================================================
-- create_table(:products)
-> 0.0160s
== CreateProducts: migrated (0.0160s) =========================================

== AddPrice: migrating ========================================================
-- add_column(:products, :price, :decimal, {:precision=>8, :scale=>2, :default=>
0.0})
rake aborted!
You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occured while evaluating nil.[][/quote]
不知道什么问题。。。google之。在ror的讨论版里得知。。。
这个问题可能是因为decimal的支持问题。。。

改用edge版本是个方法。。。另外可以选择用sql语句倒入。。。
对于edge版本我是不了解。更没信心。于是还是sql导入把。。。


class AddPrice < ActiveRecord::Migration

def self.up

#add_column :products, :price, :decimal, :precision => 8, :scale => 2, :default => 0

execute "ALTER TABLE products ADD COLUMN price DECIMAL(8,2) NOT NULL"

end


def self.down
remove_column :products, :price
end
end


接下来看到显示价格问题.
希望把28.95显示为更为友好的$28.95...
$(*%U(@$*%
我显示成$0.28...
突然发现...原来第二版的英文书也不可靠...
最可靠的方法大概是花10几块美元买一pdf..可以随时更新的版本....
快被气坏了...

书中用
module StoreHelper
def format_price(amount)
dollars, cents = amount.divmod(100)
sprintf("$%d.%02d", dollars, cents)
end
end

在helper里面写了一个方法来解决这个问题.
并不难懂...
但是在最新的代码文件中....
他用了更简单的方法...
直接在view里面.也就是需要显示价格的页面中..
直接使用了.number_to_currency这个方法解决了一切问题...

也就是说..rails本身提供这个方法...如同java的某些工具类一般...

我必须要说...rails的官方文档可真不怎么友好...

不过依然足够好到可以找到我想找到的东西了...
[url]
http://api.rubyonrails.org/classes/ActionView/Helpers/NumberHelper.html#M000449[/url]
[quote]number_to_currency(number, options = {})

Formats a number into a currency string. The options hash can be used to customize the format of the output. The number can contain a level of precision using the precision key; default is 2 The currency type can be set using the unit key; default is "$" The unit separator can be set using the separator key; default is "." The delimiter can be set using the delimiter key; default is "," Examples:

number_to_currency(1234567890.50) => $1,234,567,890.50
number_to_currency(1234567890.506) => $1,234,567,890.51
number_to_currency(1234567890.50, {:unit => "£", :separator => ",", :delimiter => ""}) => £1234567890,50
[/quote]

rails的优点之一么?
避免重复造轮子?
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值