def initialize(user=nil, attributes={})
@user = user
(self.class.car_fields & attributes.keys.map{|i| i.to_sym }).each do |f|
car[f] = attributes[f] if attributes.key?(f)
end
validate!
end
attributes = { "has_car" => "true", "has_truck" => "true", "has_boat" => "true", "color" => "blue value", "size" => "large value" }
Car.new(user, attributes)
在我的模型中,属性不会更新以进行验证。
但是,如果我传递带有所有符号的散列,它将起作用。
attributes_symbols = { :has_car => "true", :has_truck => "true", :has_boat => "true", :color => "blue value", :size=> "large value" }
Car.new(user, attributes_symbols)
答案 0 :(得分:1)
因为
attributes.keys.map{|i| i.to_sym }
您要将每个键映射为一个符号,然后在它们为字符串键的情况下以attributes
作为符号进行访问。
所以您最终会做类似的事情:
{ "has_car" => "true", "has_truck" => "true", "has_boat" => "true", ... }[:has_car]
# nil
可能的解决方案是创建一个新变量,在attributes
上调用document:
indifferent_access_attributes = attributes.with_indifferent_access
(self.class.car_fields & indifferent_access_attributes.keys.map(&:to_sym)).each do |field|
seller[field] = indifferent_access_attributes[field]
end
另一种方法是只定义键的格式,并在整个过程中使用它。因此,请勿映射到符号attributes
。