[英]Rails FactoryGirl for model that belongs_to 2 other models
I have 3 following models like this: 我有以下3种模型:
# model/timeline.rb
class Timeline
belongs_to :series
belongs_to :creator
end
def series_belongs_to_creator
if creator_id
creator = Creator.find_by id: creator_id
related_series = creator.series.find_by id: series_id
errors.add(:series_id, :not_found_series) unless related_series
end
end
# model/creator.rb
class Creator
has_many :timelines
has_many :series, through: :contents
end
# model/series.rb
class Series
has_many :timelines
has_many :creators, through: :contents
end
This is not many to many relation, timelines
table has two fields creator_id
and series_id
beside another fields. 这不是多对多的关系,
timelines
表在另一个字段旁边有两个字段creator_id
和series_id
。 creator_id
and series_id
must be entered when create Timeline and i have a method series_belongs_to_creator
to validates series_id
must belong to creator_id
to create successful. 创建时间轴时必须输入
creator_id
和series_id
并且我有一个方法series_belongs_to_creator
来验证series_id
必须属于creator_id
才能成功创建。 So how should I write factory for timeline model if using FactoryGirl. 因此,如果使用FactoryGirl,我应该如何为时间轴模型编写工厂。 Im so confused about Unit test in Rails.
我对Rails中的单元测试感到困惑。
If you're using Rails 5, you have to keep in mind that belongs_to
is no longer optional by default: https://blog.bigbinary.com/2016/02/15/rails-5-makes-belong-to-association-required-by-default.html 如果您使用的是Rails 5,则必须记住默认情况下,
belongs_to
不再是可选的: https : //blog.bigbinary.com/2016/02/15/rails-5-makes-belong-to-association -required-by-default.html
So creator_id
will always need to be present unless you specify the relation is optional. 因此,除非您指定该关系是可选的,否则
creator_id
将始终需要存在。
For the factories, you're going to end up with something like this (FactoryGirl was recently renamed to FactoryBot): http://www.rubydoc.info/gems/factory_bot/file/GETTING_STARTED.md#Associations 对于工厂,您将最终得到这样的结果(FactoryGirl最近被重命名为FactoryBot): http ://www.rubydoc.info/gems/factory_bot/file/GETTING_STARTED.md#Associations
FactoryBot.define do
factory :timeline do
creator
series
end
end
FactoryBot.define do
factory :creator do
...
end
end
FactoryBot.define do
factory :series do
...
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.