简体   繁体   中英

factorygirl association

I have an ad factory but how to assign it to user.ads attribute? i've tried

@ad = user.ads.build(:ad)

but that didn't work for me

FactoryGirl.define do
 factory :user do
  name     "My"
  email    "my@example.com"
 end

 factory :ad do
  title "Ola"
  description "Hello"
  user
 end
end


let(:user) { FactoryGirl.create(:user) }
#so i don't type it like this:
@ad = user.ads.build(title: "Lorem ipsum",description: "Lorem ipsum")
subject { @ad }
let(:user) { FactoryGirl.create(:user) }    
5.times { FactoryGirl.create(:ad, user: user) }

user.ads #=> array of ads

Of course it'll will work only if you setup the associations in the User and Ad models appropriately.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM