Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 当父项已保存时,如何处理对多个子项无效的验证?_Ruby On Rails_Ruby - Fatal编程技术网

Ruby on rails 当父项已保存时,如何处理对多个子项无效的验证?

Ruby on rails 当父项已保存时,如何处理对多个子项无效的验证?,ruby-on-rails,ruby,Ruby On Rails,Ruby,我有两门课: class Article < ActiveRecord::Base has_many :article_tags has_many :tags, through: :article_tags end class ArticleTag < ActiveRecord::Base belongs_to :article belongs_to :tag end class Tag < ActiveRecord::Base validates :nam

我有两门课:

class Article < ActiveRecord::Base
  has_many :article_tags
  has_many :tags, through: :article_tags
end
class ArticleTag < ActiveRecord::Base
  belongs_to :article
  belongs_to :tag
end
class Tag < ActiveRecord::Base
  validates :name, format: /\A\p{Alpha}*\z/
end

我看不出你需要担心什么:)

最后一行代码将通过。没有问题,因为标记对象没有持久化-它是
新的

该项在数据库中,但新的“标记”对象不在数据库中。它只在记忆中。只有当您尝试将对象保存到数据库中时,才会触发验证规则

在控制台中尝试以下操作:

> item = Item.find(params[:id])
> item.tags << Tag.new(name: '1&+') 
> item.tags[0]
#=> #<Tag:abcd0123> {
#  id: nil
#  name: '1&+'
#  ....
# } 
> item.tags[0].save!
#=> ActiveRecord::RecordInvalid: Validation failed
>item=item.find(参数[:id])
>item.tags item.tags[0]
#=> # {
#身份证号码:无
#名称:“1&+”
#  ....
# } 
>item.tags[0]。保存!
#=>ActiveRecord::RecordInvalid:验证失败

我的问题似乎过于简化了。你是对的,这段代码是有效的,但如果我使用的是
has\u many through:…
,就不行了。我已经更新了我的问题。@DanielRikowski,我还没有在控制台中测试过很多,但我重复了你们的结论。无论何处
保存时,对象必须经过验证,并且应该能够在
concat
item = Item.find(params[:id])
item.tags << Tag.new(name: '1&+')   # Exception here!
def concat(*records)
  unless owner.new_record?
    records.flatten.each do |record|
      raise_on_type_mismatch(record)
      record.save! if record.new_record?                 # Exception here!
    end
  end
  super
end
> item = Item.find(params[:id])
> item.tags << Tag.new(name: '1&+') 
> item.tags[0]
#=> #<Tag:abcd0123> {
#  id: nil
#  name: '1&+'
#  ....
# } 
> item.tags[0].save!
#=> ActiveRecord::RecordInvalid: Validation failed