0

この記事について: activerecord オブジェクトの追跡

accept_nested_attributes_for を使用して、どのフィールドが大きな形式で変更されるかを知る必要があります。

現在、フォームは期待どおりに機能しています。さらに、ユーザーの変更に関する「ログ履歴」を作成しています。

ハッシュ マッピングを試してみましたが、モデルが小さくないため非常に複雑です。上記の記事について話すと、変更を追跡するためのより良い方法が存在する可能性があります。

私のモデルは(必要な場合):

class Customer < ActiveRecord::Base
  has_many   :addresses

  attr_accessible :nom, :prenom, :langue, :nationalite, :codeFiscal, :hidden_status, :subscribed
  attr_accessible :addresses_attributes, allow_destroy: true

  accepts_nested_attributes_for :addresses
end


class Address < ActiveRecord::Base
  belongs_to :customer
  has_many   :telephones

  attr_accessible :flag, :societe, :titre, :persContact, :rue, :rue1, :nopostal, :lieu, :pays
  attr_accessible :hidden_status
  attr_accessible :telephones_attributes

  accepts_nested_attributes_for :telephones, :reject_if => :all_blank, :allow_destroy => true
end


class Telephone < ActiveRecord::Base
  belongs_to :address

  attr_accessible :typeNumero, :numeroTel
end

(モデルは非常に正常です)。

アイデアはありますか?ハッシュをマップする必要がある場合は、その方法について少しサンプルがありますか?

前もって感謝します

4

1 に答える 1

0

上記の記事と同じいくつかのオプション(Beerlingtonに感謝)の後、私は欲しかった:

これを読んでください: ActiveRecord::Dirty

def update
    @customer = Customer.find(params[:id])
    @customer.assign_attributes(params[:customer])
    if @customer.valid?
      # If changued I revise the record in the model
      @customer = @customer.requires_log if @customer.changed?
      # and very useful: @customer.changes gives you an array con every changue
      @customer.save
    end
    # similar for addresses and phones but into a loop:
    # @customer.addresses.each do |address|   ...  end
    # I didn't put it because it is repetitive
  end

手順で重要なことは次のとおりです。

  1. 代わりに assign_attributes を適用するには、保存する前に変更を追跡します。
  2. この特定のケースでは、有効に適用されますか? 正しい変更のみを追跡します。
  3. 変更を処理してから、保存などを行います。
于 2012-10-16T02:24:33.890 に答える