简体   繁体   中英

How to specify file type for a variable, in the model file?

In one of my model files I would like to specify for a variable (called xml_file) that it should be an xml file. What I've tried so far generated error messages.

Attempt 1

validates  :xml_file,         presence: true,
                              content_type: %w(application/xml)

On rake test this generated the error ArgumentError: Unknown validator: 'ContentTypeValidator' .

Attempt 2

VALID_XML_REGEX = %w(xml)
validates  :xml_file,         presence: true,
                              format: { with: VALID_XML_REGEX }

This on testing generated the error ArgumentError: A regular expression or a proc or lambda must be supplied as :with .

Attempt 3 : Create its own method

validates  :xml_file_format
private
def xml_file_format
  validates :xml_file, format: /.xml/
end

This didn't work either and generated the error ArgumentError: You need to supply at least one validation .

Therefore, my question: how to specify the variable 'xml_file' should be an xml file in the model file?

You seem to be confounding 2 separate things:

  1. XML file
  2. Path to an XML file

You are validating the Path to an XML file, which does not have a content_type. (AAMOF, XML files don't have a content_type either, but that is a separate topic.)

According to the Rails Guides , you can use:

format: { with: /\.xml\z/ }

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