2012-05-15 171 views
0

我是新来的Rails。我正在使用服务层来保持我的控制器精简。我所有的服务层文件位于app/services/domainapp/services/applicationapp/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 

所以我有两个问题:

  1. 我知道我的控制器代码不好。如何改进?
  2. 我的服务不会自动加载在生产和开发环境。为什么?

对不起,我英文不好。感谢您的每一个建议和帮助。

回答

4

有没有什么不理由希望通过服务使用的模型和抽象模型互动?

自动加载你的服务,你应该包括你的config/application.rb中

您也有不良记录(invlid记录或无效的语句)的双重检查,你的用户体验在里面自动加载config.autoload_paths服务路径将不变,为什么记录没有保存,所以没有理由嵌套ifs。你的控制器应该知道这个动作是否成功

+0

我在API中使用服务层。所以我需要将我的业务逻辑移至服务层。 – Zeck

+0

你建立一个API,或者你消耗的第三方API?如果你正在建立一个api层,你最好把它移到它自己的命名空间中,如果你正在使用它应该属于一个模型 –

+0

哦,我明白了。谢谢。我正在构建一个API。 – Zeck