我正在尝试将一些业务逻辑从我的一个控制器中移出,StoreController
并移到一个新的Store::CreateService
服务对象中。最近学习了服务,这似乎不是实现它们的既定模式。我在尝试调用受保护的方法时遇到错误。我显然可以将逻辑从那些受保护的方法中直接移入execute
,但我的理解是这对 Rails 应该没问题。
undefined local variable or method `find_and_set_account_id' for #<Store::CreateService:0x00007f832f8928f8>
这是服务对象
module Store
class CreateService < BaseService
def initialize(user, params)
@current_user, @params = user, params.dup
end
def execute
@store = Store.new(params)
@store.creator = current_user
find_and_set_account_id
if @store.save
# Make sure that the user is allowed to use the specified visibility level
@store.members.create(
role: "owner",
user: current_user
)
end
after_create_actions if @store.persisted?
@store
end
end
protected
def after_create_actions
event_service.create_store(@store, current_user)
end
def find_and_set_account_id
loop do
@store.account_id = SecureRandom.random_number(10**7)
break unless Store.where(account_id: account_id).exists?
end
end
end