首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ActiveRecord::Associations::CollectionProxy中的Access属性

ActiveRecord::Associations::CollectionProxy中的Access属性
EN

Stack Overflow用户
提问于 2014-10-15 14:21:19
回答 1查看 691关注 0票数 1

我正在尝试编写一个自定义函数,如果关联对象的数量为>=4,该函数将引发错误。

我想知道如何访问包含的散列中的键/值并对其运行验证。

如果我这么做

代码语言:javascript
复制
animal = FactoryGirl.create(:animal, images_count: 4)
a = animal.animal_images
ap(a)

我把这个还给你

代码语言:javascript
复制
#<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

代码语言:javascript
复制
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测试,并在自定义验证函数中执行逻辑。

我以为我的测试会像这样

代码语言:javascript
复制
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

只是为了暂时通过(添加错误消息),而没有逻辑

代码语言:javascript
复制
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

但似乎测试没有通过第一行

代码语言:javascript
复制
ActiveRecord::RecordInvalid:
Validation failed: Max of 3 images allowed

以上内容将抛出在控制台中。

这是我的工厂

代码语言:javascript
复制
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

我可能会尽可能地向后走,有人有什么建议吗?

谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-10-15 16:49:27

我正在尝试编写一个自定义函数,如果关联对象的数量为>=4,该函数将引发错误。

你让事情变得太复杂了。如果您只想计算集合中的记录数,那么只需执行animal.animal_images.size.。所以你的模型会是这样的:

代码语言:javascript
复制
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
end
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26384946

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档