首页 > 解决方案 > Rails 用一种形式创建 2 个相同的模型

问题描述

我正在开发一个用户提交一个表单并将其保存到用水模型中的项目。然后他们需要在目标模型中制定目标。目标模型与用水模型具有相同的属性,因此在创建用水对象时,我需要同时创建一个目标对象。然后,当用户返回设定目标时,他们将获得属性的子集,他们可以对其进行编辑并与初始结果进行比较。

以下是模型:

    class Waterusage < ApplicationRecord
  belongs_to :user

  before_validation :calculate_totals

  def calculate_totals
    self.home_usage = get_home_usage
    self.outdoor_usage = get_outdoor_usage
    self.vehicle_usage = get_vehicle_usage
    self.power_usage = get_power_usage
    self.indirect_source_usage = get_indirect_source_usage
    self.household_total = get_household_total
    self.individual_total = get_individual_total
  end

  def get_household_total
    home_usage + outdoor_usage + vehicle_usage + power_usage + indirect_source_usage
  end

  def get_individual_total
    household_total / household_size
  end

  def get_home_usage
    shower_total + bath_total + bathroom_sink_total + toilet_total + 
    kitchen_total + dishwashing_total + laundry_total + greywater
  end

  def get_outdoor_usage
    lawn_total + swimming_total
  end

  def get_vehicle_usage
    (0.735 * miles) + carwash_total
  end

  def get_power_usage
    statewater * percent_statewater / 100
  end

  def get_indirect_source_usage
    (household_size*(shopping + paper_recycling + plastic_recycling + can_recycling + textile_recycling + diet)) + (200 * pet_cost / 30)
  end

  ... (Insert many sub calculations here of attributes in the waterusages schema)
end

目标模型是相同的。

在目标控制器中,它需要使用与同一 current_user 关联的 waterusages 实例创建一个新实例。

目标控制器需要独立于用水量来编辑它的属性。

如何设置 targets.new 等于 waterusage.new ?在其中一个控制器中,模型?

标签: mysqlruby-on-railsmodel-view-controllersimple-form

解决方案


在你的goals_controller.rb,你可以这样做:
waterusage_params = waterusage.attributes.except('id', 'created_at', 'updated_at') # assuming that you have an instance of Waterusage goal = Goal.create(waterusage_params)


推荐阅读