服务层和控制器

时间:2012-05-15 01:05:08

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-3.2

我是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. 我的服务不会自动加载到生产和开发环境中。为什么?
  3. 抱歉英语不好。感谢您的建议和帮助。

1 个答案:

答案 0 :(得分:4)

您是否有理由不想使用模型并通过服务抽象模型交互?

要自动加载您的服务,您应该在config / application.rb中的autoload config.autoload_paths中包含服务路径

您还对错误记录(invlid记录或无效声明)进行了双重检查,无论为何未保存记录,您的用户体验都将保持相同,因此没有理由使用嵌套ifs。您的控制器应该只知道操作是否成功