新手问题 ActiveRecord Model 使用 hash 创建的对象字段全是 nil

excosy · 2015年04月22日 · 最后由 serco 回复于 2015年04月23日 · 2141 次阅读
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 ?

:name=> "dfsd" 或者 name: "dlfsd"

去掉这行 attr_accessor :id, :name, :title, :image, :full_price, :discount, :currency, :created_at, :updated_at

#1 楼 @dandananddada 不是这个问题,用符号做 key 的 hash new 出来还是 nil

rails4 已经不让这么用 attr_accessor 了,attr_accessor 只能用来声明虚拟属性 在 controller 里使用 hash 创建 model 对象,必须在 controller 显示声明你允许的属性,具体方法参见 strong paramters 的文档 http://edgeapi.rubyonrails.org/classes/ActionController/StrongParameters.html

#2 楼 @serco 成功了,可是这是为什么呢?

#4 楼 @azhao 被 strong paramters 替代的不是 attr_accessible 吗?attr_accessor 是 ruby 方法不是 rails 方法啊

#5 楼 @excosy 字段默认 ActiveRecord 已经帮你定义了方法,你使用 attr_accessor 反而覆盖了本身的方法,所以删除就好。

需要 登录 后方可回复, 如果你还没有账号请 注册新账号