简体   繁体   中英

Ruby on Rails - Paperclip :allow_blank with if statement

Some use case background: I am not using Paperclip for avatars or things like that. I want people to make "submissions" that can contain either a file OR a link, depending on the category of the submission they previously chose (the actual file is being uploaded to a table called Submission Details which has a foreign key to Submissions). Some categories have a "link" type, and some categories have an "image" or a "PDF" type. If they select the link category, that subsequent URL info is stored in a separate column than the image/attachment column.

Here is the code in my model to determine which is which:

def nonlink?
  if submission.category.submission_file_type == "Mixed (PDF and Images)" || submission.category.submission_file_type == "Images Only"
    return true
  else
    return false
  end
end

So ideally I would want :allow_blank if :nonlink? is true or false in the column validation area of the model.

My first question is, does validates_attachment_presence allow for :allow_blank? If it doesn't, what is the best alternative.

Secondly, what is the syntax for creating an if statement with :allow_blank in a model? Right now I have this but not sure it's right:

validates_attachment_presence :attachment, allow_blank: true, if: [:nonlink? == false]

Would appreciate any thoughts, thanks!

Solved this by doing an extra validation line containing validates_presence_of instead of just validates. I made two separate methods, nonlink and link, with one looking like:

validates_presence_of :attachment, if: :nonlink?

Using this I was able to get rid of :allow_blank entirely.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM