使空白参数[] nil [英] Make blank params[] nil
问题描述
当用户提交表单并将某些字段留空时,它们将在DB中保存为空白。我想遍历params [:user]集合(例如),如果一个字段为空,在更新属性之前将其设置为nil。我不知道该怎么做,虽然作为我知道迭代创建新对象的唯一方式:
When a user submits a form and leaves certain fields blank, they get saved as blank in the DB. I would like to iterate through the params[:user] collection (for example) and if a field is blank, set it to nil before updating attributes. I can't figure out how to do this though as the only way I know to iterate creates new objects:
coll = params[:user].each do |c|
if c == ""
c = nil
end
end
感谢。
推荐答案
通过在控制器中使用过滤器来影响模型保存或更新时的行为。我认为一个更清洁的方法将是一个 before_save
回调在模型或观察者。这样,无论是通过控制器,控制台还是运行批处理过程,您都会得到相同的行为。
Consider what you're doing here by using filters in the controller to affect how a model behaves when saved or updated. I think a much cleaner method would be a before_save
call back in the model or an observer. This way, you're getting the same behavior no matter where the change originates from, whether its via a controller, the console or even when running batch processes.
示例:
class Customer < ActiveRecord::Base
NULL_ATTRS = %w( middle_name )
before_save :nil_if_blank
protected
def nil_if_blank
NULL_ATTRS.each { |attr| self[attr] = nil if self[attr].blank? }
end
end
这会产生预期的行为:
>> c = Customer.new
=> #<Customer id: nil, first_name: nil, middle_name: nil, last_name: nil>
>> c.first_name = "Matt"
=> "Matt"
>> c.middle_name = "" # blank string here
=> ""
>> c.last_name = "Haley"
=> "Haley"
>> c.save
=> true
>> c.middle_name.nil?
=> true
>>
这篇关于使空白参数[] nil的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!