我使用 Apache Commons XMLConfiguration 进行配置。现在我需要一个基于模式的验证。但是我在将 xsd 添加到 XMLConfiguration 时遇到问题。 xsd 位于应用程序 jar 文件中。
如果我使用 Java SE 的方法,验证运行没有问题:
private void checkSchema(final Path path)
throws SAXException, ParserConfigurationException, IOException
{
final URL urlXsd = getClass().getResource(ConfigMain.SCHEMA_RESOURCE_PATH);
final SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
final Schema schema = sf.newSchema(urlXsd);
final Validator validator = schema.newValidator();
final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
final DocumentBuilder db = dbf.newDocumentBuilder();
final Document doc = db.parse(path.toFile());
validator.validate(new DOMSource(doc));
}
但是如果我将 XMLConfiguration 与 DefaultEntityResolver 一起使用,我将不会成功。
xmlConfig = new XMLConfiguration();
final URL urlXsd = getClass().getResource(SCHEMA_RESOURCE_PATH);
resolver.registerEntityId("configuration", urlXsd);
xmlConfig.setEntityResolver(resolver);
xmlConfig.setSchemaValidation(true);
我遇到以下异常:
Caused by: org.xml.sax.SAXParseException; systemId: file:/C:/.../config_default.xml; lineNumber: 2; columnNumber: 16; cvc-elt.1: Cannot find the declaration of element 'configuration'.
“配置”是 config_default.xml 的根元素。我认为这意味着它找不到 xsd。
我的第一个问题,我必须在 resolver.registerEntityId("configuration", urlXsd); 的第一个参数中输入什么?模式的公共(public) ID 是什么? documentation仅显示带有 DTD 公共(public) ID 的示例。
这里是简化的模式和 xml -> xml:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
</configuration>
架构:
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema"
<xs:element name="configuration">
</xs:element>
</xs:schema>
更新:我的测试基于 dbank 的回答:
package de.company.xmlschematest;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.dom.DOMSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.XMLConfiguration;
import org.apache.commons.logging.LogFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
public class App
{
private final XMLConfiguration xmlConfig = new XMLConfiguration();
private static final Logger LOG = LoggerFactory.getLogger(App.class);
private static final String CONFIG_FILENAME_DEFAULT = "config_default.xml";
private static final String CONFIG_FILENAME_LOCAL =
"C:\\Data\\config_current.xml";
private static final Path CONFIG_PATH_LOCAL = Paths.get(
CONFIG_FILENAME_LOCAL);
private static final String SCHEMA_FILENAME = "config_schema.xsd";
/* package */ static final String SCHEMA_RESOURCE_PATH = "/" + SCHEMA_FILENAME;
private static final String CONFIG_DEFAULT_RESOURCE_PATH = "/" +
CONFIG_FILENAME_DEFAULT;
private static final org.apache.commons.logging.Log LOG_SEC = LogFactory.getLog(App.class);
public App()
{
try
{
LOG_SEC.debug("JCL");
xmlConfig.setLogger(LOG_SEC);
final URL urlXsd = getClass().getResource(SCHEMA_RESOURCE_PATH);
final SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
final Schema schema = sf.newSchema(urlXsd);
final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setSchema(schema);
final DocumentBuilder db = dbf.newDocumentBuilder();
xmlConfig.setDocumentBuilder(db);
xmlConfig.setSchemaValidation(true);
}
catch (SAXException | ParserConfigurationException ex)
{
LOG.error("Loading error", ex);
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
System.out.println("XmlSchemaTest started");
final App app = new App();
app.loadConfig();
System.out.println("Finished");
}
private void loadConfig()
{
if(Files.exists(CONFIG_PATH_LOCAL))
{
try
{
xmlConfig.clear();
LOG.debug("Loading config {}", CONFIG_PATH_LOCAL);
xmlConfig.setFile(CONFIG_PATH_LOCAL.toFile());
xmlConfig.refresh();
LOG.info("Current config loaded");
}
catch (final ConfigurationException ex)
{
LOG.error("Loading of current config file has failed", ex);
loadDefault();
}
}
else
{
LOG.info("Local configuration is not available");
loadDefault();
}
}
private void loadDefault()
{
try
{
xmlConfig.clear();
LOG.debug("Loading config " + CONFIG_FILENAME_DEFAULT);
final File oldConfig = xmlConfig.getFile();
xmlConfig.setURL(getClass().getResource(
CONFIG_DEFAULT_RESOURCE_PATH));
if(oldConfig != null && oldConfig.exists())
{
oldConfig.delete();
}
xmlConfig.refresh();
xmlConfig.save(CONFIG_FILENAME_LOCAL);
LOG.info("Default config loaded");
}
catch (final ConfigurationException ex)
{
throw new IllegalStateException("The default config file is "
+ "not available", ex);
}
}
}
现在我已经使用无效的 xml 对其进行了测试,但我在输出中只看到一个错误。没有抛出异常。
XmlSchemaTest started
18:23:16.263 [main] DEBUG de.company.xmlschematest.App - JCL
18:23:16.325 [main] DEBUG de.company.xmlschematest.App - Loading config C:\Data\config_current.xml
18:23:16.327 [main] DEBUG o.a.c.c.ConfigurationUtils - ConfigurationUtils.locate(): base is C:\Data, name is config_current.xml
18:23:16.328 [main] DEBUG o.a.c.c.DefaultFileSystem - Could not locate file config_current.xml at C:\Data: unknown protocol: c
18:23:16.331 [main] DEBUG o.a.c.c.ConfigurationUtils - Loading configuration from the path C:\Data\config_current.xml
18:23:16.332 [main] DEBUG o.a.c.c.ConfigurationUtils - ConfigurationUtils.locate(): base is C:\Data, name is config_current.xml
18:23:16.332 [main] DEBUG o.a.c.c.DefaultFileSystem - Could not locate file config_current.xml at C:\Data: unknown protocol: c
18:23:16.332 [main] DEBUG o.a.c.c.ConfigurationUtils - Loading configuration from the path C:\Data\config_current.xml
[Error] config_current.xml:29:21: cvc-complex-type.2.4.a: Invalid content was found starting with element 'number'. One of '{name}' is expected
18:23:16.356 [main] INFO de.company.xmlschematest.App - Current config loaded
Finished
更新 - xml 中 xsd 的路径: 我认为基于回调的处理不是很好。根据你的第一个建议,我已经用 xsd 的路径在 xml 中进行了测试。但这仅针对一条路径运行。
package de.company.xmlschematest;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.dom.DOMSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.XMLConfiguration;
import org.apache.commons.logging.LogFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;
/**
*
* @author RD3
*/
public class App
{
private final XMLConfiguration xmlConfig = new XMLConfiguration();
private static final Logger LOG = LoggerFactory.getLogger(App.class);
private static final String CONFIG_FILENAME_DEFAULT = "config_default.xml";
private static final String CONFIG_FILENAME_LOCAL =
"C:\\Data\\config_current.xml";
private static final Path CONFIG_PATH_LOCAL = Paths.get(
CONFIG_FILENAME_LOCAL);
private static final String SCHEMA_FILENAME = "config_schema.xsd";
/* package */ static final String SCHEMA_RESOURCE_PATH = "/" + SCHEMA_FILENAME;
private static final String CONFIG_DEFAULT_RESOURCE_PATH = "/" +
CONFIG_FILENAME_DEFAULT;
private static final org.apache.commons.logging.Log LOG_SEC = LogFactory.getLog(App.class);
public App()
{
LOG_SEC.debug("JCL");
xmlConfig.setLogger(LOG_SEC);
xmlConfig.setSchemaValidation(true);
}
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
System.out.println("XmlSchemaTest started");
final App app = new App();
app.loadConfig();
System.out.println("Finished");
}
private void loadConfig()
{
if(Files.exists(CONFIG_PATH_LOCAL))
{
try
{
xmlConfig.clear();
LOG.debug("Loading config {}", CONFIG_PATH_LOCAL);
xmlConfig.setFile(CONFIG_PATH_LOCAL.toFile());
xmlConfig.refresh();
LOG.info("Current config loaded");
}
catch (final ConfigurationException ex)
{
LOG.error("Loading of current config file has failed", ex);
loadDefault();
}
}
else
{
LOG.info("Local configuration is not available");
loadDefault();
}
}
private void loadDefault()
{
try
{
xmlConfig.clear();
LOG.debug("Loading config " + CONFIG_FILENAME_DEFAULT);
final File oldConfig = xmlConfig.getFile();
xmlConfig.setURL(getClass().getResource(
CONFIG_DEFAULT_RESOURCE_PATH));
if(oldConfig != null && oldConfig.exists())
{
oldConfig.delete();
}
xmlConfig.refresh();
xmlConfig.save(CONFIG_FILENAME_LOCAL);
LOG.info("Default config loaded");
}
catch (final ConfigurationException ex)
{
throw new IllegalStateException("The default config file is "
+ "not available", ex);
}
}
}
第一次运行确实处理得当。它从基于 xsi:noNamespaceSchemaLocation="config_schema.xsd"的 jar 中获取 xsd。然后将从 jar 加载的默认配置写入本地文件系统。我检查了书面文件,找不到奇怪的想法。然后我再次运行示例应用程序,但现在出现以下错误:
XmlSchemaTest started
10:49:58.730 [main] DEBUG de.company.xmlschematest.App - JCL
10:49:58.738 [main] DEBUG de.company.xmlschematest.App - Loading config C:\Data\config_current.xml
10:49:58.740 [main] DEBUG o.a.c.c.ConfigurationUtils - ConfigurationUtils.locate(): base is C:\Data, name is config_current.xml
10:49:58.741 [main] DEBUG o.a.c.c.DefaultFileSystem - Could not locate file config_current.xml at C:\Data: unknown protocol: c
10:49:58.744 [main] DEBUG o.a.c.c.ConfigurationUtils - Loading configuration from the path C:\Data\config_current.xml
10:49:58.745 [main] DEBUG o.a.c.c.ConfigurationUtils - ConfigurationUtils.locate(): base is C:\Data, name is config_current.xml
10:49:58.745 [main] DEBUG o.a.c.c.DefaultFileSystem - Could not locate file config_current.xml at C:\Data: unknown protocol: c
10:49:58.746 [main] DEBUG o.a.c.c.ConfigurationUtils - Loading configuration from the path C:\Data\config_current.xml
10:49:58.795 [main] ERROR de.company.xmlschematest.App - Loading of current config file has failed
org.apache.commons.configuration.ConfigurationException: Error parsing file:/C:/Data/config_current.xml
at org.apache.commons.configuration.XMLConfiguration.load(XMLConfiguration.java:1014) ~[commons-configuration-1.10.jar:1.10]
at org.apache.commons.configuration.XMLConfiguration.load(XMLConfiguration.java:972) ~[commons-configuration-1.10.jar:1.10]
at org.apache.commons.configuration.XMLConfiguration$XMLFileConfigurationDelegate.load(XMLConfiguration.java:1647) ~[commons-configuration-1.10.jar:1.10]
at org.apache.commons.configuration.AbstractFileConfiguration.load(AbstractFileConfiguration.java:324) ~[commons-configuration-1.10.jar:1.10]
at org.apache.commons.configuration.AbstractFileConfiguration.load(AbstractFileConfiguration.java:261) ~[commons-configuration-1.10.jar:1.10]
at org.apache.commons.configuration.AbstractFileConfiguration.load(AbstractFileConfiguration.java:238) ~[commons-configuration-1.10.jar:1.10]
at org.apache.commons.configuration.AbstractFileConfiguration.refresh(AbstractFileConfiguration.java:889) ~[commons-configuration-1.10.jar:1.10]
at org.apache.commons.configuration.AbstractHierarchicalFileConfiguration.refresh(AbstractHierarchicalFileConfiguration.java:335) ~[commons-configuration-1.10.jar:1.10]
at de.company.xmlschematest.App.loadConfig(App.java:110) [classes/:na]
at de.company.xmlschematest.App.main(App.java:68) [classes/:na]
Caused by: org.xml.sax.SAXParseException: cvc-elt.1: Cannot find the declaration of element 'configuration'.
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:203) ~[na:1.8.0_31]
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:134) ~[na:1.8.0_31]
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:437) ~[na:1.8.0_31]
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:368) ~[na:1.8.0_31]
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:325) ~[na:1.8.0_31]
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.handleStartElement(XMLSchemaValidator.java:1906) ~[na:1.8.0_31]
at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.startElement(XMLSchemaValidator.java:746) ~[na:1.8.0_31]
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(XMLNSDocumentScannerImpl.java:379) ~[na:1.8.0_31]
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl$NSContentDriver.scanRootElementHook(XMLNSDocumentScannerImpl.java:605) ~[na:1.8.0_31]
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:3138) ~[na:1.8.0_31]
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(XMLDocumentScannerImpl.java:880) ~[na:1.8.0_31]
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:606) ~[na:1.8.0_31]
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:117) ~[na:1.8.0_31]
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:510) ~[na:1.8.0_31]
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:848) ~[na:1.8.0_31]
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:777) ~[na:1.8.0_31]
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:141) ~[na:1.8.0_31]
at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:243) ~[na:1.8.0_31]
at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:348) ~[na:1.8.0_31]
at org.apache.commons.configuration.XMLConfiguration.load(XMLConfiguration.java:1006) ~[commons-configuration-1.10.jar:1.10]
... 9 common frames omitted
10:49:58.796 [main] DEBUG de.company.xmlschematest.App - Loading config config_default.xml
10:49:58.862 [main] INFO de.company.xmlschematest.App - Default config loaded
Finished
他找不到 xsd,但 xml 文件中的路径是正确的,与第一次运行时相同。为什么第一次fun能找到xsd,第二次就找不到?
第二个问题,是不是XMLConfiguration所有可能的日志输出?
更新 3: 我再次测试发现,如果我将 xsd 放入本地文件系统,那么第二次运行没有问题。我认为问题是在 xml 中定义路径时对 xsd 的相对搜索。
可以从本地文件系统加载 xml 并使用位于 jar 文件中的模式进行验证吗?我在调用 load() 或 refresh() 时搜索没有回调和直接异常处理的解决方案。
最好的问候,
最佳答案
resolver.registerEntityId() 的第一个参数是用于映射到特定实体 URL 的公共(public) ID。我怀疑“配置”是否是此处使用的正确值。但是,我认为这里存在一些混淆,您甚至不需要在您的案例中费心使用实体解析器。
假设您有一个 mySchema.xsd:
<?xml version="1.0" encoding="UTF-8" ?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="configuration">
</xs:element>
</xs:schema>
假设 mySchema.xml 位于 mypackage.stackoverflow 包中的一个 jar 中,并且该 jar 位于 C:\path\to\myJar.jar(因为您似乎使用的是 Windows)。让你的 config_default.xml 看起来像这样:
<?xml version="1.0" encoding="UTF-8"?>
<configuration xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="jar:file:/C:/path/to/myJar.jar!/mypackage/stackoverflow/mySchema.xsd">
</configuration>
然后您应该能够加载 config_default.xml,它将引用 mySchema.xsd 进行验证。
使用 Commons Configuration v1.10 :
XMLConfiguration config = new XMLConfiguration();
config.setFileName("config_default.xml");
config.setSchemaValidation(true);
// This will throw a ConfigurationException if the XML document does not
// conform to its Schema.
config.load();
注意: 以下事实证明与提问者的问题无关,但我将其留在这里以供引用。
如果您想以编程方式设置模式文件,您可以通过设置 XMLConfiguration 的 DocumentBuilder 来实现。
import java.io.File;
import javax.xml.XMLConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.XMLConfiguration;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class CommonsConfigTester {
public static void main(String[] args) {
XMLConfiguration config = new XMLConfiguration();
config.setFileName("config_default.xml");
config.setSchemaValidation(true);
try {
Schema schema = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(new File("mySchema.xsd"));
DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
docBuilderFactory.setSchema(schema);
DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
//if you want an exception to be thrown when there is invalid xml document,
//you need to set your own ErrorHandler because the default
//behavior is to just print an error message.
docBuilder.setErrorHandler(new ErrorHandler() {
@Override
public void warning(SAXParseException exception) throws SAXException {
throw exception;
}
@Override
public void error(SAXParseException exception) throws SAXException {
throw exception;
}
@Override
public void fatalError(SAXParseException exception) throws SAXException {
throw exception;
}
});
config.setDocumentBuilder(docBuilder);
config.load();
} catch (ConfigurationException | ParserConfigurationException | SAXException e) {
//handle exception
e.printStackTrace();
}
}
}
关于java - Commons XMLConfiguration 和模式验证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28770257/
给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru
我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co
我想安装一个带有一些身份验证的私有(private)Rubygem服务器。我希望能够使用公共(public)Ubuntu服务器托管内部gem。我读到了http://docs.rubygems.org/read/chapter/18.但是那个没有身份验证-如我所见。然后我读到了https://github.com/cwninja/geminabox.但是当我使用基本身份验证(他们在他们的Wiki中有)时,它会提示从我的服务器获取源。所以。如何制作带有身份验证的私有(private)Rubygem服务器?这是不可能的吗?谢谢。编辑:Geminabox问题。我尝试“捆绑”以安装新的gem..
我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i
我希望我的UserPrice模型的属性在它们为空或不验证数值时默认为0。这些属性是tax_rate、shipping_cost和price。classCreateUserPrices8,:scale=>2t.decimal:tax_rate,:precision=>8,:scale=>2t.decimal:shipping_cost,:precision=>8,:scale=>2endendend起初,我将所有3列的:default=>0放在表格中,但我不想要这样,因为它已经填充了字段,我想使用占位符。这是我的UserPrice模型:classUserPrice回答before_val
鉴于我有以下迁移:Sequel.migrationdoupdoalter_table:usersdoadd_column:is_admin,:default=>falseend#SequelrunsaDESCRIBEtablestatement,whenthemodelisloaded.#Atthispoint,itdoesnotknowthatusershaveais_adminflag.#Soitfails.@user=User.find(:email=>"admin@fancy-startup.example")@user.is_admin=true@user.save!ende
我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss
我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/
我有一些非常大的模型,我必须将它们迁移到最新版本的Rails。这些模型有相当多的验证(User有大约50个验证)。是否可以将所有这些验证移动到另一个文件中?说app/models/validations/user_validations.rb。如果可以,有人可以提供示例吗? 最佳答案 您可以为此使用关注点:#app/models/validations/user_validations.rbrequire'active_support/concern'moduleUserValidationsextendActiveSupport:
当我的预订模型通过rake任务在状态机上转换时,我试图找出如何跳过对ActiveRecord对象的特定实例的验证。我想在reservation.close时跳过所有验证!叫做。希望调用reservation.close!(:validate=>false)之类的东西。仅供引用,我们正在使用https://github.com/pluginaweek/state_machine用于状态机。这是我的预订模型的示例。classReservation["requested","negotiating","approved"])}state_machine:initial=>'requested