【问题标题】:Rails Creating 2 Identical Models with one formRails 用一种形式创建 2 个相同的模型
【发布时间】:2018-10-21 09:59:35
【问题描述】:

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

以下是模型:

    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 ?在其中一个控制器中,模型?

【问题讨论】:

  • 请具体说明您的问题。虽然您可能可以访问您的代码并且您知道问题所在,但仅通过阅读本段,您很难理解您在问什么以及您想要实现什么。
  • 看看这里的回答能不能帮到你。 stackoverflow.com/questions/24746906/…
  • 我从模型中添加了一些代码来提供帮助。模型是相同的,只是第二个控制器需要使用来自第一个模型的数据创建一个实例。有关更多说明,请参见上文。

标签: mysql ruby-on-rails model-view-controller simple-form


【解决方案1】:

在你的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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多