给定以下代码:
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)
First:您对定义类的关系是错误的。应该是复数!:单词
秒:验证也是错误的。它也应该是复数形式。例如验证:words
通过这种方式,它期望带有name word的字段不是空的,而不是关系。
尝试将示例代码更改为:
word = Word.first
definition = Definition.new
definition.words = [word]
definition.save