当前位置: 首页 > 知识库问答 >
问题:

accepts_nested_attributes_for在验证外键时出现问题

范宏大
2023-03-14

我使用的是Ruby on Rails V3.2.2。我想解决在使用accepts_nested_attributes_forvalidates_associatedRoR方法时与外键验证相关的问题。也就是说,我有以下模型类:

class Article < ActiveRecord::Base
  has_many :category_associations, :foreign_key => 'category_id'

  accepts_nested_attributes_for :category_associations, :reject_if => lambda { |attributes| attributes[:category_id].blank? }
  validates_associated :category_associations
end

class CategoryAssociation < ActiveRecord::Base
  belongs_to :article, :foreign_key => 'article_id'
  belongs_to :category, :foreign_key => 'category_id'

  validates :article_id, :presence => true
  validates :category_id, :presence => true
end
class ArticlesController < ApplicationController
  def new
    @article = Article.new
    5.times { @article.category_associations.build }

    # ...
  end

 def create
   @article = Article.new(params[:article])

   if @article.save
     # ...
   else
     # ...
   end
 end
end
{:"category_associations.article_id"=>["can't be blank"], :category_associations=>["is invalid"]}

但是,如果我注释掉categoryAssociation模型类中的validates:article_id,:presence=>true,它会按预期工作,但是不验证外键似乎不是一个正确的方法。

如果我注释掉文章模型类中的validates_Associated:category_Associations,我仍然会得到错误:

{:"category_associations.article_id"=>["can't be blank"]}

共有1个答案

锺离声
2023-03-14

使用INVERSE_OF链接关联,然后验证关联对象的存在,而不是实际外键的存在。

文档中的示例:

class Member < ActiveRecord::Base
  has_many :posts, inverse_of: :member
  accepts_nested_attributes_for :posts
end

class Post < ActiveRecord::Base
  belongs_to :member, inverse_of: :posts
  validates_presence_of :member
end
 类似资料:
  • 我使用squeelize.js和SQLite-database,遇到了一个为外键设置值的问题。我有以下代码: Sequelize在DB中创建MessageModel-row,但当它试图生成TodoModel时,它会出现以下错误: 生成得SQL: 我的TodoModel表如下所示: 我在SQLite中使用了“sequelize”:“^5.1.0”。 MyConfig文件:

  • 问题内容: 验证失败后,为什么从Hibernate收到UnsupportedOperationException?我希望有一个ConstraintViolationException。 以下是我的DAO。通过验证后即可正常工作。我正在使用Hibernate和Hibernate Validator4。我正在使用Websphere 8.0。我认为WebSphereExtendedJtaPlatform

  • 我试图创建一个表达式验证方法,以确保传递到函数中的帐号是否有效。如果是,则返回true,如果为false,则返回false。 但是我正在经历一个错误: 我已经看了一些堆栈溢出问题,但我似乎无法弄清楚我在代码中做错了什么。 代码: 我从https://www.freeformatter.com/java-regex-tester.html#ad-output

  • 我试图在我的项目中使用Hibernate验证器,但它不起作用。在以下行: 我得到以下例外情况: 我发现这个问题似乎与我的问题很相似。他将他的解决方案描述为 我想我的问题也是一样的。在http://hibernate.org/validator/documentation/getting-start/it上说: 这会传递地引入对Bean验证API的依赖关系(javax.Validation:vali

  • 我有一个XML文档,需要在其中验证签名。SignedInfo元素具有指定算法“http://www.w3.org/2001/10/xml-exc-c14n#”的元素CanonicalizationMethod,还具有一个子元素InclusiveNamespaces,该子元素具有填充的PrefixList属性,如下所示: 我使用以下代码创建我的C14Transform对象: 其中来自属性。 我遇到的

  • 我正在尝试用Itext 5.4和BouncyCastle 1.49验证PDF签名(它是通过Adobe Reader X用我的数字证书手动签名的)。 但是验证结果总是出乎意料的,下面是我的Java代码: 控制台显示:完整性检查OK?真