mysql - 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 ?在其中一个控制器中,模型?
解决方案
在你的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)
推荐阅读
- rest - gitlab api:获取一个组的所有项目(带有子组)
- c# - 在 MVC 中创建数据库类
- c# - 在显示之前编辑表单的外观
- php - 以编程方式在 wordpress 多站点中创建类别和子类别
- python - 是否可以为鼻子测试提供“设置-geterator-functions”?
- laravel - 如何获得具有两个或多个特定条件的行?
- ruby-on-rails - 从 2.3 切换到 2.4 时出现包更新错误
- c - 来自 C 标准库的 mergesort() 的链接错误
- git - 有没有办法从你当前的 HEAD 历史记录中的某个地方删除一个提交?
- android - 在android中记录屏幕的选定区域