问题描述
在我的模型中,我有一个after_create回调来触发该方法:
class Job < ActiveRecord::Base
after_create :update_vanity_url
private
def update_vanity_url
self.vanity_url = '/jobs/' + company.slug + '/' + slug + '/' + id.to_s + '/'
end
end
这将为我的工作设置一个自定义URL,但是,当我尝试在优惠券工厂中使用该URL时,该URL未保存.优惠券是在未分配工作的情况下创建的.仅当使用优惠券时,它才与一个作业配对.我称其为已执行:
FactoryGirl.define do
factory :coupon do
code { rand(25**25) }
percent_discount { rand(100**1) }
start_at { Time.now }
end_at { 30.day.from_now }
trait :executed do |c|
association :job, factory: [:job, :purchased]
c.executed_at { Time.now }
end
end
end
理想情况下,我希望能够调用有效的FactoryGirl.create(:coupon, :executed)
,但永远不会调用after_create....
有关此设置的更多详细信息,请参见此处使用可选的模型关联来启用FactoryGirl Factory
下面的每个问题注释,我添加了我的路线部分和更新:
路线
resources :jobs, only: [:new] do
collection do
post 'new', to: 'jobs#create'
end
get '/review', to: 'reviews#new'
patch '/review', to: 'reviews#update'
get '/payment', to: 'payments#new'
patch '/payment', to: 'payments#update'
end
match '/jobs/:company_slug/:job_slug/:id', via: :get, to: 'jobs#show'
我研究了几个小时,这就是我发现可以使用的方法.原来不是FactoryGirl,而是模型本身...我想...
def update_vanity_url
self.vanity_url = '/jobs/' + company.slug + '/' + slug + '/' + id.to_s + '/'
save
end
In my model, I have an after_create callback that triggers the method:
class Job < ActiveRecord::Base
after_create :update_vanity_url
private
def update_vanity_url
self.vanity_url = '/jobs/' + company.slug + '/' + slug + '/' + id.to_s + '/'
end
end
This sets up a custom url for my jobs, however, when I try to use this in my coupon factory it is not being saved. The coupon is created without a job assigned. Only when the coupon is used is it paired with one job. I referred to that as executed:
FactoryGirl.define do
factory :coupon do
code { rand(25**25) }
percent_discount { rand(100**1) }
start_at { Time.now }
end_at { 30.day.from_now }
trait :executed do |c|
association :job, factory: [:job, :purchased]
c.executed_at { Time.now }
end
end
end
Ideally, I would like to be able to call FactoryGirl.create(:coupon, :executed)
which works but the after_create is never called... Thoughts?
More details of this setup are covered here Rails FactoryGirl Factory with optional model association
Per issue comments below, I have added my routes section and updates:
Routes
resources :jobs, only: [:new] do
collection do
post 'new', to: 'jobs#create'
end
get '/review', to: 'reviews#new'
patch '/review', to: 'reviews#update'
get '/payment', to: 'payments#new'
patch '/payment', to: 'payments#update'
end
match '/jobs/:company_slug/:job_slug/:id', via: :get, to: 'jobs#show'
I researched this for hours, and this is what I found to work. It turns out it was not FactoryGirl, rather the model itself... I think...
def update_vanity_url
self.vanity_url = '/jobs/' + company.slug + '/' + slug + '/' + id.to_s + '/'
save
end
这篇关于Rails FactoryGirl特征与模型after_create回调的关联未设置vanity_url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!