牌語備忘録 -pygo

あくまでもメモです。なるべくオフィシャルの情報を参照してください。

牌語備忘録 -pygo

Railsの『update_attribute』と『update_attributes』の違いでハマらないために気をつけること

第18回 Rails勉強会@東北 で教えてもらいました。

結論を先に

バリデーション『するか』、『しない』か。
※Rails3レシピブックに掲載されて無い。

ソース見てみる persistence.rb

rvmでインストールしたときのパス

  • ~/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-3.1.3/lib/active_record/persistence.rb

update_attribute

バリデーションしない

    def update_attribute(name, value)
      name = name.to_s
      raise ActiveRecordError, "#{name} is marked as readonly" if self.class.readonly_attributes.include?(name)
      send("#{name}=", value)
      save(:validate => false)     #<- ここ
    end

update_attributes

バリデーションする

    def update_attributes(attributes, options = {})
      # The following transaction covers any possible database side-effects of the
      # attributes assignment. For example, setting the IDs of a child collection.
      with_transaction_returning_status do
        self.assign_attributes(attributes, options)
        save
      end
    end