1
我在文檔之間有多對多的關係。通過關係RSpec測試不驗證has_many
說我有document1
和document2
。我有許多桌子,那裏有父母和孩子。
document.rb
has_many :child_relationships, :class_name => "DocumentRelationship", :foreign_key => "child_id", :dependent => :destroy
has_many :parents, :through => :child_relationships, :source => :parent
has_many :parent_relationships, :class_name => "DocumentRelationship", :foreign_key => "parent_id", :dependent => :destroy
has_many :children, :through => :parent_relationships, :source => :child
document_relationship.rb
belongs_to :parent, :class_name => "Document", :foreign_key => "parent_id"
belongs_to :child, :class_name => "Document", :foreign_key => "child_id"
validates_uniqueness_of :child_id, :scope => [:parent_id]
validates_presence_of :parent_id
validates_presence_of :child_id
validate :obeys_chronology
def obeys_chronology
errors.add(:child_id, "must be created after its parent") if child_id.to_i < parent_id.to_i
errors.add(:child_id, "cannot be its own parent") if child_id.to_i == parent_id.to_i
end
如果我說document2.children << document1
它適當地驗證失敗,但我不知道怎麼寫一個測試此。
有沒有更好的方法來做到這一點?
我剛剛試過。 失敗/錯誤:d2.children << d1 ActiveRecord :: RecordInvalid: 驗證失敗:必須在其父代後創建子代 #./spec/models/document_spec.rb:65:in'block(3 levels)in' –
Cyrus
2012-01-05 02:09:38