Make a field optional in rails

后端 未结 3 593
[愿得一人]
[愿得一人] 2021-01-23 05:08

I use paperclip to attach an avatar to users, which works fine but when a new user attempts to register it complains about the avatar bieng too small and not of the right type.<

相关标签:
3条回答
  • 2021-01-23 05:25

    I didn't use paperclip, but in general in Rails you can add condition to decide if validations should be run.

    validates_attachment_size :avatar, 
      :less_than => 1.megabytes, 
      :unless => "avatar.blank?"
    

    You should add similar condition to all validations that affects avatar. If you want know more take a look here.

    0 讨论(0)
  • 2021-01-23 05:30

    I don't know if this is gonna work but try:

    validates_attachment_size :avatar, :less_than => 1.megabytes, :if => avatar_changed?
    validates_attachment_content_type :avatar, :content_type => ['image/jpeg', 'image/png', 'image/gif'], :if => avatar_changed?
    
    0 讨论(0)
  • 2021-01-23 05:39

    It's more like:

    validates_attachment_size :avatar, :less_than => 1.megabytes, :unless => "avatar_content_type.blank?"

    0 讨论(0)
提交回复
热议问题