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
だから私は2つの質問があります:
- 私のコントローラーコードは良くないことを知っています。それを改善する方法は?
- 私のサービスは、本番環境および開発環境に自動的にロードされません。なんで?
英語が下手でごめんなさい。すべてのアドバイスと助けてくれてありがとう。