0

我想从我的 maintenance_controller 更新我的车型。我该怎么做呢?或者这是错误的方法?我的维护视图获取应存储在车辆模型中的里程表值。

class Maintenance < ActiveRecord::Base
  belongs_to :vehicle

维护控制器:

@maintenance = Maintenance.new
@maintenance.invoice = params[:invoice]
....
@vehicle = Vehicle.find(params[:vehicle_id])
@vehicle.odometer = params[:odometer]
....
4

2 回答 2

1

@vehicle.save

As @MrYoshiji pointed out, the code is fine, just needed to save it.

于 2013-06-04T12:38:58.537 回答
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 太方便了,导致耦合增加/难以维护代码。不过,您的里程可能会有所不同。

于 2013-06-03T21:27:59.387 回答