2016年12月5日 星期一

validate / validates

剛在看rails tutorial的時候碰到了一個錯誤訊息
You need to supply at least one validation
錯誤是指向
validates :picture_size
google一下發現因為我不應該用validates,應該要用沒有s的validate
正確完整的code如下
#Listing 13.65: Adding validations to images.
class Micropost < ApplicationRecord
  belongs_to :user
  default_scope -> { order(created_at: :desc) }
  mount_uploader :picture, PictureUploader
  validates :user_id, presence: true
  validates :content, presence: true, length: { maximum: 140 }
  validate  :picture_size

  private

    # Validates the size of an uploaded picture.
    def picture_size
      if picture.size > 5.megabytes
        errors.add(:picture, "should be less than 5MB")
      end
    end
end
validates是用在預設的validation,但是因為picture_size是自定的,所以要用validate
validate會去找有沒有和你給他的parameter一樣的method
validate  :picture_size
他會去找有沒有
def picture_size
end
Written with StackEdit.

沒有留言:

張貼留言