a = {"name"=>"dfsd", "title"=>"dwq", "image"=>"sad", "full_price"=>"234", "discount"=>"2", "currency"=>"USD"}
Sale.new(a) #=> #<Sale id: nil, name: nil, title: nil, image: nil, full_price: nil, discount: nil, currency: nil, created_at: nil, updated_at: nil>
其中 Sale 是这样定义的:
class Sale < ActiveRecord::Base
# attr_accessor id, 商品短名,商品全名,原始价,折扣价,货币种类,创建于,更新于
attr_accessor :id, :name, :title, :image, :full_price, :discount, :currency, :created_at, :updated_at
validates :name, length: { maximum: 20 }, presence: true
validates :image, presence: true
validates :full_price, format: { with: /\A\d+(\.\d\d)?\z/ }, presence: true
validates :discount, format: { with: /\A\d+(\.\d\d)?\z/ }, presence: true
validates :currency, format: { with: /\A[A-Z]{3}\z/ }, presence: true
end
可以确定不是数据验证的问题,因为去除数据验证后依然未能创建非空对象,ruby -v 2.2.1,rails -v 4.2.1 另外,访问 ActiveRecord Model 对象字段规范的方法是 object[:attribute] 还是 object.attribute ?