由于我使用'updated_at'(专门用于原子提要)的性质,我需要避免在记录是更新时更新updated_at字段保存没有任何更改。为了实现这个目标我读了,结束了以下内容:当通过has_many保存时,Rails抛出保存错误(参数1为0)
module ActiveRecord
class Base
before_validation :clear_empty_strings
# Do not actually save the model if no changes have occurred.
# Specifically this prevents updated_at from being changed
# when the user saves the item without actually doing anything.
# This especially helps when synchronizing models between apps.
def save
if changed?
super
else
class << self
def record_timestamps; false; end
end
super
class << self
remove_method :record_timestamps
end
end
end
# Strips and nils strings when necessary
def clear_empty_strings
attributes.each do |column, value|
if self[column].is_a?(String)
self[column].strip.present? || self[column] = nil
end
end
end
end
end
能正常工作在我的所有车型,除了我的电子邮件模型。电子邮件可以有许多发件箱。发件箱基本上是一个双列模型,它包含订阅者(电子邮件地址:)和电子邮件(发送给订户的电子邮件)。当我更新发件箱的属性,然后保存电子邮件时,我得到(保存方法中的'super'调用)保存时的(参数1 for 0)错误。
Email.rb
has_many :outboxes, :order => "subscriber_id", :autosave => true
Outbox.rb
belongs_to :email, :inverse_of => :outboxes
belongs_to :subscriber, :inverse_of => :outboxes
validates_presence_of :subscriber_id, :email_id
attr_accessible :subscriber_id, :email_id
更新:我也注意到,当我改变关联模型的 '改变' 阵列没有被填充。
@email.outboxes.each do |out|
logger.info "Was: #{ out.paused }, now: #{ !free }"
out.paused = !free
end unless @email.outboxes.empty?
@email.save # Upon saving, the changed? method returns false...it should be true