我有两个模型Post
和Image
。如果没有images
,则无法创建帖子。
class Post < ActiveRecord::Base
has_many :images
validates :images , presence: true
end
class Image < ActiveRecord::Base
belongs_to :post
validates :post_id , presence: true
validates :name , presence: true
end
现在,我正在为factory girl
和post
设置image
。我和image
工厂女孩没关系,但无法设置post
工厂女孩应该有图像。
#image
FactoryGirl.define do
factory :image do
name "something"
post_id 121
end
end
#post
FactoryGirl.define do
factory :post do
title "foo bar"
after(:create) do |post,evaluator|
create_list :image , 3 , post: post
end
end
end
但我仍然在post
images should be present
上结束了验证错误。这个错误确实有意义,但如何解决这个问题。
答案 0 :(得分:1)
这对我有用
FactoryGirl.define do
factory :post do
title "foo bar"
after(:build) do |post,evaluator|
post.images << (build_list :image , 3 , post: post)
end
end
end