将ActionController的create / destroy方法移动到模型中

时间:2015-07-14 05:45:30

标签: ruby-on-rails ruby-on-rails-4

好的,我已经在ActionController中添加了一些代码,用于创建和销毁方法,以便使用Web浏览器在AWS上创建实例。我想将这些因素纳入模型,以便我可以从rake脚本执行相同的功能。

控制器中的代码:

  def create
    @instance = Instance.new(instance_params)
    @instance.user_id = current_user.id
    @instance.password = SecureRandom.hex(8)
    @instance.name = Haikunator.haikunate
    ec2 = Aws::EC2::Client.new(region: @instance.region)
    regions = YAML.load_file("#{Rails.root}/config/regions.yml")
    resp = ec2.run_instances({
      image_id: regions[@instance.region]['image'],
      instance_type: "t1.micro",
      min_count: 1,
      max_count: 1,
      key_name: regions[@instance.region]['key_name'],
      security_groups: ["launch-wizard-4"],
    })

    @instance.aws_instance_id = resp.instances.first.instance_id  

    respond_to do |format|
      if @instance.save
        @instance.delay.ec2_on_running
        format.html do
          redirect_to action: "index"
        end
        format.json { render json: @instance.to_json }
      else
        format.html { render :new }
        format.json { render json: @instance.errors, status: :unprocessable_entity }
      end
    end
  end

我应该如何将其纳入模型?

1 个答案:

答案 0 :(得分:1)

def create
  @instance = Instance.new.create_from_params(instance_params, current_user.id)

  respond_to do |format|
    if @instance.persisted?
      format.html do
        redirect_to action: "index"
      end
      format.json { render json: @instance.to_json }
    else
      format.html { render :new }
      format.json { render json: @instance.errors, status: :unprocessable_entity }
    end
  end
end


class Instance

  def create_from_params params, user_id
    assign_attributes(params)
    self.user = user_id
    self.password = SecureRandom.hex(8)
    self.name = Haikunator.haikunate
    self.aws_instance_id = runned_instances.first.instance_id
    delay_ec2 if salf.save
    self
  end

  private

  def ec2
    @ec2 ||= Aws::EC2::Client.new(region: region)
  end

  def regions
    YAML.load_file("#{Rails.root}/config/regions.yml")
  end

  def runned_instances
    ec2.run_instances({
          image_id: regions[@instance.region]['image'],
          instance_type: "t1.micro",
          min_count: 1,
          max_count: 1,
          key_name: regions[@instance.region]['key_name'],
          security_groups: ["launch-wizard-4"],
        }).instances
  end

  def delay_ec2
    delay.ec2_on_running
  end
end