【发布时间】:2016-03-22 06:22:55
【问题描述】:
这是我的文件:
word.rb
class Word < ActiveRecord::Base
has_many :word_answers, dependent: :destroy
accepts_nested_attributes_for :word_answers, allow_destroy: true,
reject_if: lambda {|attribute| attribute[:word_id].blank?}
end
word_answer.rb
class WordAnswer < ActiveRecord::Base
belongs_to :word
validates :content, uniqueness: true, presence: true
end
有什么方法可以验证 word.rb 中 word_answer.rb 的validates :content, uniqueness: true, presence: true 吗?
导轨 4。
我尝试了validates_associated :word_answers,但它不起作用。
我要实现的是
(1)如果我提交Word,如果没有WordAnswer会报错。
(2)如果我提交Word,如果有BLANK WordAnswer,就会报错。
(3)如果验证是WordAnswer是错误的,我提交Word会报错。
【问题讨论】:
-
既然您在
word_answer模型中执行了这些验证,为什么还需要在您的word模型中进行验证? -
因为它们是nested_attributes。它会在没有任何 word_answers 的情况下保存单词
-
为什么要让
content独一无二?你想做什么? -
这就像一个问题。 Word = 问题,WordAnswer = 选择。
-
我的意思是,你的
content应该是唯一的吗?你为什么要把你的专栏命名为内容,因为你希望它是独一无二的?想象一下?
标签: ruby-on-rails ruby ruby-on-rails-4