2013-02-18 108 views
0

由于我使用'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 

回答

0

......叹了口气。花了无数小时试图找到解决方案后,我碰到了this。我是否知道'save'方法实际上需要一个论点,我早就想到了这一点。显然看着source在这方面没有帮助。我所要做的只是在save方法中添加一个args = {}参数,并将其传递给'super',并且所有内容都正在工作。保存未修改的记录而不更新时间戳,使用时间戳保存已修改的记录并保存关联而没有错误。

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(args={}) 

    if changed? 
     super args 
    else 
     class << self 
     def record_timestamps; false; end 
     end 
     super args 
     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 
相关问题