0

Given this code:

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    |       |
+---------------+---------+------+-----+---------+-------+

When I call:

word = Word.first
word.definitions.create!

I get:

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

1 回答 1

1

首先:您在定义类上的关系是错误的。应该是复数!:字

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

这样,它期望名称单词的字段不为空而不是关系。

尝试将您的示例代码更改为:

word = Word.first
definition = Definition.new
definition.words = [word]
definition.save
于 2013-01-17T17:35:49.767 回答