草庐IT

java - 重复注释错误 - 但在哪里?

coder 2024-03-26 原文

简而言之,首先 - 我收到此异常消息:

serverError: class javax.faces.el.EvaluationException Duplicate annotation for class: interface javax.validation.constraints.Size: @javax.validation.constraints.Size(groups=[], min=0, message={javax.validation.constraints.Size.message}, payload=[], max=128)

我的代码由 1 个表实体类、一个 EJB、一个“业务类”和一个 JSF 页面组成;当我调用 EntityManager.merge() 时发生异常。里面只有 1 个带有 'max = 128' 的注解:

@Size(max = 128)
@Column(name = "name")
private String name;

唯一有重复注释的地方是:

@Entity
@Table(name = "attributes", schema = "office_db")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Attributes.findAll", query = "SELECT a FROM Attributes a"),
    @NamedQuery(name = "Attributes.findById", query = "SELECT a FROM Attributes a WHERE a.id = :id"),
    @NamedQuery(name = "Attributes.findByName", query = "SELECT a FROM Attributes a WHERE a.name = :name"),
    @NamedQuery(name = "Attributes.findByType", query = "SELECT a FROM Attributes a where a.type.id = :type")
})

但我认为这应该是合法的,因为它是由 Netbeans 8.2 从数据库表生成的。

现在有更多细节。首先是表格:

mysql> show create table attributes\G
*************************** 1. row ***************************
       Table: attributes
Create Table: CREATE TABLE `attributes` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `parent` int(11) DEFAULT NULL,
  `type` int(11) DEFAULT NULL,
  `name` varchar(128) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `parent_ix` (`parent`),
  KEY `type_ix` (`type`),
  CONSTRAINT `attributes_parent_fk` FOREIGN KEY (`parent`) REFERENCES `attributes` (`id`),
  CONSTRAINT `attributes_type_fk` FOREIGN KEY (`type`) REFERENCES `attributes` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1301 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
1 row in set (0.03 sec)

接下来是实体类:

import (...stuff...)

@Entity
@Table(name = "attributes")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Attributes.findAll", query = "SELECT a FROM     Attributes a"),
    @NamedQuery(name = "Attributes.findById", query = "SELECT a FROM Attributes a WHERE a.id = :id"),
    @NamedQuery(name = "Attributes.findByName", query = "SELECT a FROM Attributes a WHERE a.name = :name"),
    @NamedQuery(name = "Attributes.findByType", query = "SELECT a FROM Attributes a where a.type.id = :type")
})
public class Attributes implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id")
    private Integer id;
    @Size(max = 128)
    @Column(name = "name")
    private String name;
    @OneToMany(mappedBy = "parent")
    private Collection<Attributes> attributesCollection;
    @JoinColumn(name = "parent", referencedColumnName = "id")
    @ManyToOne
    private Attributes parent;
    @OneToMany(mappedBy = "type")
    private Collection<Attributes> attributesCollection1;
    @JoinColumn(name = "type", referencedColumnName = "id")
    @ManyToOne
    private Attributes type;
    private static final Logger logger=
            Logger.getLogger(Attributes.class.getName());

    public Attributes() {
    }

    public Attributes(Integer id) {
        this.id = id;
    }
    public Attributes(Integer id, Integer parent, Integer type, String name) {
        logger.info("OFFICE Attributes constructor 3 id: "+id+", parent:     "+parent+", type: "+type+", name: "+name);
        this.parent=new Attributes();
        this.type=new Attributes();
        this.id = id;
        this.parent.setId(parent);
        this.type.setId(type);
        this.name = name;
    }

    public Attributes(Integer parent, Integer type, String name) {
        logger.info("OFFICE Attributes constructor 4 parent: "+parent+", type: "+type+", name: "+name);
        this.parent=new Attributes();
        this.type=new Attributes();
        this.parent.setId(parent);
        this.type.setId(type);
        this.name = name;
        logger.info("OFFICE Attributes constructor 4a");
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @XmlTransient
    public Collection<Attributes> getAttributesCollection() {
        return attributesCollection;
    }

    public void setAttributesCollection(Collection<Attributes> attributesCollection) {
        this.attributesCollection = attributesCollection;
    }

    public Attributes getParent() {
        return parent;
    }

    public void setParent(Attributes parent) {
        this.parent = parent;
    }

    @XmlTransient
    public Collection<Attributes> getAttributesCollection1() {
        return attributesCollection1;
    }

    public void setAttributesCollection1(Collection<Attributes> attributesCollection1) {
        this.attributesCollection1 = attributesCollection1;
    }

    public Attributes getType() {
        return type;
    }

    public void setType(Attributes type) {
        this.type = type;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Attributes)) {
            return false;
        }
        Attributes other = (Attributes) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "docdb.Attributes[ id=" + id + " ]";
    }
}

EJB 或 session 类:

import (...stuff...)

@Stateless
public class AttributesSession {
    @PersistenceContext(unitName ="officePU")
    private EntityManager em;
    private static final Logger logger=
            Logger.getLogger(AttributesSession.class.getName());

    public List<Attributes>findAttributes(){
        TypedQuery<Attributes> query=
                    em.createNamedQuery("Attributes.findAll",Attributes.class);
        return query.getResultList();
    }

    public Attributes findAttributeById(Long id){
        TypedQuery<Attributes> query=
                em.createNamedQuery("Attributes.findById", Attributes.class);
        query.setParameter("id", id);
        return query.getSingleResult();
    }

    public Integer findChildCount(Long id){
        TypedQuery<Integer> query=em.createNamedQuery("findChildCount",Integer.class);
        query.setParameter("id", id);
        return query.getSingleResult();
    }

    public String createAttributes(Attributes attr){
        String msg="";

        try{
            em.merge(attr);
            em.flush();
        }
        catch (PersistenceException e){
            msg=e.getMessage();
        }
        return msg;
    }

    public String deleteAttributes(Attributes attr){
        String msg = "";

        try{
            em.remove(em.merge(attr));
            em.flush();
        }
        catch (PersistenceException e){
            msg=e.getMessage();
        }
        return msg;
    }
}

业务或 Controller 类:

import (...stuff...)

@Named(value = "attributesController")
@SessionScoped
public class AttributesController implements Serializable{
    @EJB private AttributesSession sess;
    private Attributes attr;
    private List<Attributes> attrList;
    private Integer id;
    private Integer parent;
    private Integer type;
    private String name;
    private String errmsg;
    private static final Logger logger=
            Logger.getLogger(AttributesController.class.getName());

    public AttributesController() {
        this.attrList = new ArrayList<>();
        this.attr = new Attributes();
    }

    public List<Attributes> getAttrList() {
        return attrList;
    }

    public List<Attributes> getAttrValueList() {
        return attrList;
    }

    ...getters and setters...

    public void clearForm(){
        this.id=null;
        this.name=null;
        this.parent=null;
        this.type=null;
        this.errmsg=null;
    }

    public String createAttributes(){
        if (this.id!=null){
            attr=new Attributes(this.id,this.parent,this.type,this.name);
        }
        else{
            attr=new Attributes(this.parent,this.type,this.name);
        }
        errmsg=sess.createAttributes(attr);
        attrList=sess.findAttributes();
        return "editattributes.xhtml";
    }

    public String deleteAttributes(){
        if (this.id!=null){
            attr=new Attributes(this.id,this.parent,this.type,this.name);
            errmsg=sess.deleteAttributes(attr);
        }
        attrList=sess.findAttributes();
        return "editattributes.xhtml";
    }

    public String listAttributes(){
        attrList=sess.findAttributes();
        return "editattributes.xhtml";
    }

    @PostConstruct
    public void updateList(){
        attrList=sess.findAttributes();
    }

    @Override
    public String toString(){
        return "Name: "+((name==null)?"":name)
                +", parent: "+((parent==null)?"":parent)
                +", type:"+((type==null)?"":type);
    }
}

最后,堆栈跟踪:

[2017-10-31T10:23:31.697+0000] [glassfish 5.0] [WARNING] [] [javax.enterprise.resource.webcontainer.jsf.lifecycle] [tid: _ThreadID=27 _ThreadName=http-listener-1(1)] [timeMillis: 1509445411697] [levelValue: 900] [[
  #{attributesController.createAttributes()}: java.lang.annotation.AnnotationFormatError: Duplicate annotation for class: interface javax.validation.constraints.Size: @javax.validation.constraints.Size(groups=[], min=0, message={javax.validation.constraints.Size.message}, payload=[], max=128)
javax.faces.FacesException: #{attributesController.createAttributes()}: java.lang.annotation.AnnotationFormatError: Duplicate annotation for class: interface javax.validation.constraints.Size: @javax.validation.constraints.Size(groups=[], min=0, message={javax.validation.constraints.Size.message}, payload=[], max=128)
        ...(deleted stuff)
        ... 35 more
Caused by: java.lang.annotation.AnnotationFormatError: Duplicate annotation for class: interface javax.validation.constraints.Size: @javax.validation.constraints.Size(groups=[], min=0, message={javax.validation.constraints.Size.message}, payload=[], max=128)
        ... (stuff deleted)
        at docdb.__EJB31_Generated__AttributesSession__Intf____Bean__.createAttributes(Unknown Source)
        at docdb.AttributesController.createAttributes(AttributesController.java:118)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:483)
        at javax.el.ELUtil.invokeMethod(ELUtil.java:304)
        at javax.el.BeanELResolver.invoke(BeanELResolver.java:535)
        at javax.el.CompositeELResolver.invoke(CompositeELResolver.java:256)
        at com.sun.el.parser.AstValue.invoke(AstValue.java:285)
        at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
        at org.jboss.weld.module.web.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
        at org.jboss.weld.module.web.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
        at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:107)
        at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
        ... 36 more
]]

[2017-10-31T10:23:31.700+0000] [glassfish 5.0] [INFO] [] [docdb.LifeCycleListener] [tid: _ThreadID=27 _ThreadName=http-listener-1(1)] [timeMillis: 1509445411700] [levelValue: 800] [[
  OFFICE END PHASE INVOKE_APPLICATION 5]]

[2017-10-31T10:23:31.701+0000] [glassfish 5.0] [INFO] [] [docdb.LifeCycleListener] [tid: _ThreadID=27 _ThreadName=http-listener-1(1)] [timeMillis: 1509445411701] [levelValue: 800] [[
  OFFICE]]

[2017-10-31T10:23:31.703+0000] [glassfish 5.0] [SEVERE] [] [javax.enterprise.resource.webcontainer.jsf.context] [tid: _ThreadID=27 _ThreadName=http-listener-1(1)] [timeMillis: 1509445411703] [levelValue: 1000] [[
  javax.faces.el.EvaluationException: java.lang.annotation.AnnotationFormatError: Duplicate annotation for class: interface javax.validation.constraints.Size: @javax.validation.constraints.Size(groups=[], min=0, message={javax.validation.constraints.Size.message}, payload=[], max=128)
        at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:101)
        at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
        at javax.faces.component.UICommand.broadcast(UICommand.java:330)
        at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:870)
        at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1418)
        at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:82)
        at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:100)
        at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:201)
        at javax.faces.webapp.FacesServlet.service(FacesServlet.java:670)
        at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1580)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:258)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
        at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:652)
        at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:591)
        at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:155)
        at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:371)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:238)
        at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:463)
        at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:168)
        at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
        at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
        at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:242)
        at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
        at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
        at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
        at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
        at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
        at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
        at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:539)
        at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
        at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
        at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
        at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
        at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:593)
        at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:573)
        at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.annotation.AnnotationFormatError: Duplicate annotation for class: interface javax.validation.constraints.Size: @javax.validation.constraints.Size(groups=[], min=0, message={javax.validation.constraints.Size.message}, payload=[], max=128)
        at sun.reflect.annotation.TypeAnnotationParser.mapTypeAnnotations(TypeAnnotationParser.java:361)
        at sun.reflect.annotation.AnnotatedTypeFactory$AnnotatedTypeBaseImpl.<init>(AnnotatedTypeFactory.java:139)
        at sun.reflect.annotation.AnnotatedTypeFactory.buildAnnotatedType(AnnotatedTypeFactory.java:65)
        at sun.reflect.annotation.TypeAnnotationParser.buildAnnotatedType(TypeAnnotationParser.java:79)
        at java.lang.reflect.Field.getAnnotatedType(Field.java:1159)
        at org.hibernate.validator.internal.metadata.provider.AnnotationMetaDataProvider.findCascadingMetaData(AnnotationMetaDataProvider.java:610)
        at org.hibernate.validator.internal.metadata.provider.AnnotationMetaDataProvider.findPropertyMetaData(AnnotationMetaDataProvider.java:231)
        at org.hibernate.validator.internal.metadata.provider.AnnotationMetaDataProvider.getFieldMetaData(AnnotationMetaDataProvider.java:220)
        at org.hibernate.validator.internal.metadata.provider.AnnotationMetaDataProvider.retrieveBeanConfiguration(AnnotationMetaDataProvider.java:128)
        at org.hibernate.validator.internal.metadata.provider.AnnotationMetaDataProvider.getBeanConfiguration(AnnotationMetaDataProvider.java:119)
        at org.hibernate.validator.internal.metadata.BeanMetaDataManager.getBeanConfigurationForHierarchy(BeanMetaDataManager.java:220)
        at org.hibernate.validator.internal.metadata.BeanMetaDataManager.createBeanMetaData(BeanMetaDataManager.java:187)
        at org.hibernate.validator.internal.metadata.BeanMetaDataManager.lambda$getBeanMetaData$0(BeanMetaDataManager.java:160)
        at org.hibernate.validator.internal.metadata.BeanMetaDataManager$$Lambda$24/1020030882.apply(Unknown Source)
        at java.util.concurrent.ConcurrentMap.computeIfAbsent(ConcurrentMap.java:324)
        at org.hibernate.validator.internal.metadata.BeanMetaDataManager.getBeanMetaData(BeanMetaDataManager.java:159)
        at org.hibernate.validator.internal.engine.ValidatorImpl.getConstraintsForClass(ValidatorImpl.java:308)
        at org.eclipse.persistence.internal.jpa.metadata.listeners.BeanValidationListener.isBeanConstrained(BeanValidationListener.java:158)
        at org.eclipse.persistence.internal.jpa.metadata.listeners.BeanValidationListener.validateOnCallbackEvent(BeanValidationListener.java:108)
        at org.eclipse.persistence.internal.jpa.metadata.listeners.BeanValidationListener.preUpdate(BeanValidationListener.java:94)
        at org.eclipse.persistence.descriptors.DescriptorEventManager.notifyListener(DescriptorEventManager.java:726)
        at org.eclipse.persistence.descriptors.DescriptorEventManager.notifyEJB30Listeners(DescriptorEventManager.java:696)
        at org.eclipse.persistence.descriptors.DescriptorEventManager.executeEvent(DescriptorEventManager.java:233)
        at org.eclipse.persistence.descriptors.changetracking.DeferredChangeDetectionPolicy.calculateChanges(DeferredChangeDetectionPolicy.java:87)
        at org.eclipse.persistence.descriptors.changetracking.AttributeChangeTrackingPolicy.calculateChangesForExistingObject(AttributeChangeTrackingPolicy.java:48)
        at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.calculateChanges(UnitOfWorkImpl.java:711)
        at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitToDatabaseWithChangeSet(UnitOfWorkImpl.java:1566)
        at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.issueSQLbeforeCompletion(UnitOfWorkImpl.java:3256)
        at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.issueSQLbeforeCompletion(RepeatableWriteUnitOfWork.java:355)
        at org.eclipse.persistence.transaction.AbstractSynchronizationListener.beforeCompletion(AbstractSynchronizationListener.java:158)
        at org.eclipse.persistence.transaction.JTASynchronizationListener.beforeCompletion(JTASynchronizationListener.java:68)
        at com.sun.enterprise.transaction.JavaEETransactionImpl.commit(JavaEETransactionImpl.java:452)
        at com.sun.enterprise.transaction.JavaEETransactionManagerSimplified.commit(JavaEETransactionManagerSimplified.java:854)
        at com.sun.ejb.containers.EJBContainerTransactionManager.completeNewTx(EJBContainerTransactionManager.java:723)
        at com.sun.ejb.containers.EJBContainerTransactionManager.postInvokeTx(EJBContainerTransactionManager.java:507)
        at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:4600)
        at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2108)
        at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2078)
        at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:220)
        at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:88)
        at com.sun.proxy.$Proxy175.createAttributes(Unknown Source)
        at docdb.__EJB31_Generated__AttributesSession__Intf____Bean__.createAttributes(Unknown Source)
        at docdb.AttributesController.createAttributes(AttributesController.java:118)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:483)
        at javax.el.ELUtil.invokeMethod(ELUtil.java:304)
        at javax.el.BeanELResolver.invoke(BeanELResolver.java:535)
        at javax.el.CompositeELResolver.invoke(CompositeELResolver.java:256)
        at com.sun.el.parser.AstValue.invoke(AstValue.java:285)
        at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
        at org.jboss.weld.module.web.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
        at org.jboss.weld.module.web.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
        at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:107)
        at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
        ... 36 more
]]

最佳答案

如果 @NamedQueries 是个问题,我会非常惊讶,顾名思义它应该是 @NamedQuery 项的列表/数组。

尝试:

@Column(name = "name", length = 128)
private String name;

既然你确信你实际上没有重复 @size,也许我们应该看看函数的重叠,@Column 注释包含相同的功能,这可能会导致冲突。

关于java - 重复注释错误 - 但在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47019186/

有关java - 重复注释错误 - 但在哪里?的更多相关文章

  1. ruby-on-rails - Rails 常用字符串(用于通知和错误信息等) - 2

    大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje

  2. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

  3. ruby-on-rails - 迷你测试错误 : "NameError: uninitialized constant" - 2

    我遵循MichaelHartl的“RubyonRails教程:学习Web开发”,并创建了检查用户名和电子邮件长度有效性的测试(名称最多50个字符,电子邮件最多255个字符)。test/helpers/application_helper_test.rb的内容是:require'test_helper'classApplicationHelperTest在运行bundleexecraketest时,所有测试都通过了,但我看到以下消息在最后被标记为错误:ERROR["test_full_title_helper",ApplicationHelperTest,1.820016791]test

  4. ruby-on-rails - 如何在 Rails View 上显示错误消息? - 2

    我是rails的新手,想在form字段上应用验证。myviewsnew.html.erb.....模拟.rbclassSimulation{:in=>1..25,:message=>'Therowmustbebetween1and25'}end模拟Controller.rbclassSimulationsController我想检查模型类中row字段的整数范围,如果不在范围内则返回错误信息。我可以检查上面代码的范围,但无法返回错误消息提前致谢 最佳答案 关键是您使用的是模型表单,一种显示ActiveRecord模型实例属性的表单。c

  5. 使用 ACL 调用 upload_file 时出现 Ruby S3 "Access Denied"错误 - 2

    我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file

  6. ruby-on-rails - 错误 : Error installing pg: ERROR: Failed to build gem native extension - 2

    我克隆了一个rails仓库,我现在正尝试捆绑安装背景:OSXElCapitanruby2.2.3p173(2015-08-18修订版51636)[x86_64-darwin15]rails-v在您的Gemfile中列出的或native可用的任何gem源中找不到gem'pg(>=0)ruby​​'。运行bundleinstall以安装缺少的gem。bundleinstallFetchinggemmetadatafromhttps://rubygems.org/............Fetchingversionmetadatafromhttps://rubygems.org/...Fe

  7. ruby - #之间? Cooper 的 *Beginning Ruby* 中的错误或异常 - 2

    在Cooper的书BeginningRuby中,第166页有一个我无法重现的示例。classSongincludeComparableattr_accessor:lengthdef(other)@lengthother.lengthenddefinitialize(song_name,length)@song_name=song_name@length=lengthendenda=Song.new('Rockaroundtheclock',143)b=Song.new('BohemianRhapsody',544)c=Song.new('MinuteWaltz',60)a.betwee

  8. ruby-on-rails - 每次我尝试部署时,我都会得到 - (gcloud.preview.app.deploy) 错误响应 : [4] DEADLINE_EXCEEDED - 2

    我是Google云的新手,我正在尝试对其进行首次部署。我的第一个部署是RubyonRails项目。我基本上是在关注thisguideinthegoogleclouddocumentation.唯一的区别是我使用的是我自己的项目,而不是他们提供的“helloworld”项目。这是我的app.yaml文件runtime:customvm:trueentrypoint:bundleexecrackup-p8080-Eproductionconfig.ruresources:cpu:0.5memory_gb:1.3disk_size_gb:10当我转到我的项目目录并运行gcloudprevie

  9. ruby-on-rails - Rails 5 Active Record 记录无效错误 - 2

    我有两个Rails模型,即Invoice和Invoice_details。一个Invoice_details属于Invoice,一个Invoice有多个Invoice_details。我无法使用accepts_nested_attributes_forinInvoice通过Invoice模型保存Invoice_details。我收到以下错误:(0.2ms)BEGIN(0.2ms)ROLLBACKCompleted422UnprocessableEntityin25ms(ActiveRecord:4.0ms)ActiveRecord::RecordInvalid(Validationfa

  10. arrays - 这是 Ruby 中 Array.fill 方法的错误吗? - 2

    这个问题在这里已经有了答案:Arraysmisbehaving(1个回答)关闭6年前。是否应该这样,即我误解了,还是错误?a=Array.new(3,Array.new(3))a[1].fill('g')=>[["g","g","g"],["g","g","g"],["g","g","g"]]它不应该导致:=>[[nil,nil,nil],["g","g","g"],[nil,nil,nil]]

随机推荐