当它与潜在复杂的用户操作相关时,我是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 太方便了,导致耦合增加/难以维护代码。不过,您的里程可能会有所不同。