我想从maintenance_controller更新我的车型。我该怎么做呢?或者这是错误的方法?我的维护视图获取应存储在车辆模型中的里程表值。
class Maintenance < ActiveRecord::Base
belongs_to :vehicle
maintenance_controller:
@maintenance = Maintenance.new
@maintenance.invoice = params[:invoice]
....
@vehicle = Vehicle.find(params[:vehicle_id])
@vehicle.odometer = params[:odometer]
....
答案 0 :(得分:1)
@vehicle.save
正如@MrYoshiji指出的那样,代码很好,只需要保存它。
答案 1 :(得分:0)
当它与潜在复杂的用户操作相关时,我是Form Objects
的忠实粉丝。 见于 http://blog.codeclimate.com/blog/2012/10/17/7-ways-to-decompose-fat-activerecord-models/。
我发现知道用户交互和ActiveRecord定义是分开的很有帮助。
例如,您可以创建MaintenanceForm类。这将用于验证用户输入并将其保留回数据库。
class MaintenanceForm
include Virtus
extend ActiveModel::Naming
include ActiveModel::Conversion
include ActiveModel::Validations
attribute :vehicle, Vehicle
attribute :odometer_reading, Integer
validates :vehicle, presence: true
validates :maintenace, presence: true
validate :odometer_is_increasing
# … more validations, as needed …
# Forms are never themselves persisted
def persisted?
false
end
def save
if valid?
persist!
true
else
false
end
end
private
def odometer_is_increasing
# ensure that we don't accept an odometer reading less than our last record, if applicable
end
# Do all of the persistence heavy-lifting here.
def persist!
Maintenance.create({
vehicle_id: vehicle.id,
odometer: odometer_reading
#
# ...include others, as needed
})
vehicle.update_attributes({
odometer: odometer_reading
#
# ...include others, as needed
})
end
end
nested_resource解决方案也可以。但我发现nested_resources太方便了,导致耦合增加/难以维护代码。但是,您的里程可能会有所不同。