我正在尝试编写一个自定义函数,如果关联对象的数量为>=4,该函数将引发错误。
我想知道如何访问包含的散列中的键/值并对其运行验证。
如果我这么做
animal = FactoryGirl.create(:animal, images_count: 4)
a = animal.animal_images
ap(a)我把这个还给你
#<ActiveRecord::Associations::CollectionProxy [
#<AnimalImage id: 520, animal_id: 158, image: "yp2.jpg", created_at: "2014-10-15 13:45:11", updated_at: "2014-10-15 13:45:11">,
#<AnimalImage id: 521, animal_id: 158, image: "yp2.jpg", created_at: "2014-10-15 13:45:11", updated_at: "2014-10-15 13:45:11">,
#<AnimalImage id: 522, animal_id: 158, image: "yp2.jpg", created_at: "2014-10-15 13:45:11", updated_at: "2014-10-15 13:45:11">,
#<AnimalImage id: 523, animal_id: 158, image: "yp2.jpg", created_at: "2014-10-15 13:45:11", updated_at: "2014-10-15 13:45:11">
]所以我想用.map
animal = FactoryGirl.create(:animal, images_count: 4)
a = animal.animal_images
map = a.each.map { |i| i.image }
if map.length >= 4
ap('MORE THAN 4 IMAGES')
end
"MORE THAN 4 IMAGES"这样就可以在CollectionProxy中迭代。但是,如何将其格式化为正确的rspec测试,并在自定义验证函数中执行逻辑。
我以为我的测试会像这样
it 'should display an error message when too many images are uploaded' do
animal = FactoryGirl.create(:animal, images_count: 4)
animal.max_num_of_images
expect(animal.errors[:base]).to include("Max of 3 images allowed")
end只是为了暂时通过(添加错误消息),而没有逻辑
class AnimalImage < ActiveRecord::Base
belongs_to :animal
validate :max_num_of_images, :if => "image?"
def max_num_of_images
errors.add(:base, "Max of 3 images allowed")
end
end但似乎测试没有通过第一行
ActiveRecord::RecordInvalid:
Validation failed: Max of 3 images allowed以上内容将抛出在控制台中。
这是我的工厂
FactoryGirl.define do
factory :animal, class: Animal do
ignore do
images_count 0
end
after(:create) do |animal, evaluator|
create_list(:animal_image, evaluator.images_count, animal: animal)
end
end
end
FactoryGirl.define do
factory :animal_image do
image { File.open("#{Rails.root}/spec/fixtures/yp2.jpg") }
end
end我可能会尽可能地向后走,有人有什么建议吗?
谢谢
发布于 2014-10-15 16:49:27
我正在尝试编写一个自定义函数,如果关联对象的数量为>=4,该函数将引发错误。
你让事情变得太复杂了。如果您只想计算集合中的记录数,那么只需执行animal.animal_images.size.。所以你的模型会是这样的:
class Animal < ActiveRecord::Base
has_many :animal_images
validate :max_num_of_images
def max_num_of_images
errors.add(:base, "Max of 3 images allowed") if self.animal_images.size >= 4
end
endhttps://stackoverflow.com/questions/26384946
复制相似问题