鉴于此代码:
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)
答案 0 :(得分:1)
首先:您对Definition类的关系是错误的。它应该是复数! :词语
第二:验证也是错误的。它也应该是复数。例如验证:单词
通过这种方式,它希望名称字的字段不是空白而不是关系。
尝试将示例代码更改为:
word = Word.first
definition = Definition.new
definition.words = [word]
definition.save