0
我是新來的Rails。我正在使用服務層來保持我的控制器精簡。我所有的服務層文件位於app/services/domain
,app/services/application
,app/services/infrastructure
。例如這裏是我公司的服務:服務層和控制器
class CompanyService
def self.create(params)
company = Company.new(params)
rst = true
ActiveRecord::Base.transaction do
begin
company.save!
rescue ActiveRecord::RecordInvalid
rst = false
rescue ActiveRecord::StatementInvalid
rst = nil
end
end
return company, rst
end
def self.update(params)
company = get_company(params[:id])
rst = true
ActiveRecord::Base.transaction do
begin
company.old_category_ids = company.category_ids
company.assign_attributes(params[:company])
decrease_category_ids = company.old_category_ids-company.category_ids
decrease_counters(decrease_category_ids)
increase_category_ids = company.category_ids-company.old_category_ids
increase_counters(increase_category_ids)
company.save!
rescue ActiveRecord::RecordInvalid
rst = false
rescue ActiveRecord::StatementInvalid
rst = nil
end
end
return company, rst
end # end update
這裏是公司負責人:
def create
@company, rst = CompanyService.create(params[:company])
if rst == true
redirect_to(admin_companies_url, notice: "Company was successfully created.")
elsif rst == false
render active_admin_template('new.html.erb')
else
redirect_to admin_companies_url, notice: "Something went wrong. Please try again."
end
end
def update
@company, rst = CompanyService.update(params)
if rst
redirect_to admin_company_url(company), notice: "Company was successfully updated."
elsif rst == false
render active_admin_template('edit.html.erb')
elsif rst == nil
redirect_to admin_companies_url, notice: "Something went wrong. Please try again."
end
end
def destroy
CompanyService.destroy(params[:id])
redirect_to admin_companies_url
end
所以我有兩個問題:
- 我知道我的控制器代碼不好。如何改進?
- 我的服務不會自動加載在生產和開發環境。爲什麼?
對不起,我英文不好。感謝您的每一個建議和幫助。
我在API中使用服務層。所以我需要將我的業務邏輯移至服務層。 – Zeck
你建立一個API,或者你消耗的第三方API?如果你正在建立一個api層,你最好把它移到它自己的命名空間中,如果你正在使用它應該屬於一個模型 –
哦,我明白了。謝謝。我正在構建一個API。 – Zeck