【问题标题】:Access attributes in ActiveRecord::Associations::CollectionProxy访问 ActiveRecord::Associations::CollectionProxy 中的属性
【发布时间】:2014-10-15 14:21:19
【问题描述】:

我正在尝试编写一个自定义函数,如果关联对象的数量为>=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

我可能会以最倒退的方式来解决这个问题,请问有人有什么建议

谢谢

【问题讨论】:

    标签: ruby-on-rails ruby activerecord ruby-on-rails-4 rspec


    【解决方案1】:

    我正在尝试编写一个自定义函数,如果关联对象的数量 >=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
    end
    

    【讨论】:

    • 谢谢,所以在动物模型而不是animal_image模型中进行验证..
    • @Richlewis 这取决于您在应用程序中执行的操作。在您的代码中,您正在测试 animal.errors[:base] 因此在动物模型中对其进行了验证,但您可以采用任何一种方式。将不得不相应地更新代码
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-18
    • 2014-04-26
    • 1970-01-01
    相关资源
    最近更新 更多