ActiveRecord :: RecordInvalid(验证失败:Word不能为空)

时间:2013-01-17 17:31:11

标签: ruby-on-rails ruby ruby-on-rails-3

鉴于此代码:

class Word < ActiveRecord::Base
  has_and_belongs_to_many :definitions
end

class Definition < ActiveRecord::Base
  has_and_belongs_to_many :word
  validates :word, presence: true
end

mysql> show columns from definitions_words;
+---------------+---------+------+-----+---------+-------+
| Field         | Type    | Null | Key | Default | Extra |
+---------------+---------+------+-----+---------+-------+
| definition_id | int(11) | NO   | PRI | NULL    |       |
| word_id       | int(11) | NO   | PRI | NULL    |       |
+---------------+---------+------+-----+---------+-------+

我打电话的时候:

word = Word.first
word.definitions.create!

我明白了:

ActiveRecord::RecordInvalid (Validation failed: Word can't be blank)

1 个答案:

答案 0 :(得分:1)

首先:您对Definition类的关系是错误的。它应该是复数! :词语

第二:验证也是错误的。它也应该是复数。例如验证:单词

通过这种方式,它希望名称字的字段不是空白而不是关系。

尝试将示例代码更改为:

word = Word.first
definition = Definition.new
definition.words = [word]
definition.save