2012-03-05 69 views
3

我似乎无法找到任何方法成功地将小数字段设置为无格式的值,因为表单正在返回空字符串。下面是手动将字段设置''无法将数值DataMapper字段设置为空值

require 'dm-core' 
require 'dm-mysql-adapter' 
require 'dm-migrations' 

DataMapper.setup(:default, 'mysql://localhost/test') 

class Product 
    include DataMapper::Resource 
    property :id, Serial 

    property :list_price, Decimal 
end 

DataMapper.finalize 

DataMapper.auto_migrate! 

p = Product.new 
puts p.save #=> true 

p = Product.new(:list_price => '') 
puts p.save #=> false 

p = Product.new(:list_price => nil) 
puts p.save #=> true 

正如你所看到的,当它没有设置,或者当它被设置为零的list_price场会很乐意节省超级简单的测试案例。但是,当我使用空白字符串时,它根本不会保存 - 它看起来不是类型转换。

看来我必须在这里忽略一些明显的东西,因为这是ORM的一个非常基本的用例。

回答

2

您可以为属性创建自己的setter方法来检查其类型。请参阅Datamapper properties documentation page上的“顶部访问器”部分。

添加:

def list_price=(new_price) 
    new_price = nil if new_price == '' 
    super 
end 

Product类将导致任何空字符串被设定为list_price值转换为零,并允许要保存的资源。

+1

虽然这可以解决问题,但手动操作似乎是荒谬的。这不就是为什么我们有ORM吗? – Emily 2012-03-06 00:00:57

+1

@Emily我发现这个相关的问题:https://github.com/datamapper/dm-core/issues/41。 “...我们决定DataMapper不负责将空字符串转换为nils”。他们承认,尽管它对webapps很有用。 – matt 2012-03-06 19:36:35

+0

有趣,谢谢。在我的搜索中,我没有反驳过。不幸的是,它似乎并没有像线程中所建议的那样将它变成dm-rails。我结束了猴子补丁'typecast'来支持它。 – Emily 2012-03-06 20:28:31