0

我有以下从控制器中切断的复杂方法:

def self.create_with_company_and_employer(job_params)
  company_attributes = job_params.delete(:company_attributes)
  employer_attributes = job_params.delete(:employer_attributes)

  new(job_params) do |job|
    job.employer = Employer.find_or_create_by_email(employer_attributes)
    company_attributes[:admin_id] = job.employer.id if Company.find_by_nip(company_attributes[:nip]).nil?
    job.company = Company.find_or_create_by_nip(company_attributes)
    Employment.create(employer_id: job.employer.id, company_id: job.company.id)
  end
end

我在这里使用两个nested_attributes 功能来创建公司和雇主。

您可以在这里找到完整的代码:https ://gist.github.com/2c3b52c35df763b6d9b4

company_attributes[:admin_id] = job.employer.id if Company.find_by_nip(company_attributes[:nip]).nil?
Employment.create(employer_id: job.employer.id, company_id: job.company.id)

基本上我想重构这两行:

4

1 回答 1

0

我看了你的要点,我认为这是一个设计问题。

  • 您的就业和工作模型似乎有些多余,但我不知道它们的实际目的究竟是什么,所以我现在无法真正帮助解决这个问题(我有一种预感,您的架构可以用属于的雇员进行改造工作)。但是,如果你真的想要,你可以使用after_create回调来管理复制:

    class Job < ActiveRecord::Base
      after_create :create_corresponding_employment
    
      def create_corresponding_employment
        Employment.create( employer_id: employer.id, company_id: company.id )
      end
    end
    

    this gets you rid of the last line of your method.

  • the other line you want to get rid of is tricky : you assign an admin_id to your company, but why would you want to do that ? In fact, you're just creating a 'hidden' relation between Company and Employer (a belongs_to one). Why do you need that ? Give more information and i can help.
  • one more thing: it is not advised to delete keys form the params, or even modify the hash directly. Use a copy.
于 2012-11-18T13:25:47.227 回答