2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

FactoryGirlで関連名を別名参照しているアソシエーションを作る

Posted at
app/models/user.rb
class User < ActiveRecord::Base
	has_many :created_events, class_name: 'Event', foreign_key: :owner_id
end
app/models/event.rb
class Event < ActiveRecord::Base
	belongs_to :owner, class_name: 'User'
end

以下の例はEventオブジェクトを生成する際に関連するUserオブジェクトも生成する

assosiation :関連名, factory: :ファクトリ名

spec/factories/event.rb
FactoryGirl.define do
	factory :event do
		title "タイトル"
		message "メッセージ"
		association :owner, factory: :user
	end
end
spec/factories/user.rb
FactoryGirl.define do
	factory :user do
		username "Johney"
		sequence(:email) { |n| "johney#{n}@test.com"}
		password "password"
    	password_confirmation "password"
	end
end

参考

http://shim0mura.hatenadiary.jp/entry/2014/06/29/002102
http://qiita.com/cooltiger/items/29d130584c97e647d845

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?