0

ネストされたフォームを持ち、関係は次のようになります

class Inspection < ActiveRecord::Base
  has_many :inspection_components
  accepts_nested_attributes_for :inspection_components

class InspectionComponent < ActiveRecord::Base
  belongs_to :inspection

InspectionComponent に入力された属性に依存するカスタム検証メソッドが Inspection にあります。検証方法 - InspectionComponent 属性が保存されていないか、Inspection の検証で使用できません。

ありがとう!

編集:物事をもう少し明確にするために、私がやろうとしていることの例を次に示します。

検査には属性ステータスがあります。InspectionComponent には属性 status もあります。

Inspection 編集フォームにはネストされた InspectionComponents があり、このフォームで各モデルのステータスを更新できます。@inspection.status は、すべての @inspection_component.status == 'complete' の場合にのみ 'complete' とマークできる必要があります。

したがって、@inspection を検証するときは、ユーザーが @inspection_component.status に入力した内容を確認できる必要があります。

明らかに、コントローラーの両方のインスタンスのパラメーターにアクセスできますが、検証が行われるモデルでは、これを行う方法がわかりません。

うまくいけば、それは明らかです、ありがとう。

4

2 に答える 2

1

わかりました。私が投稿した他の回答が他の人に役立つ場合に備えて、新しい回答を入力してください。特にあなたの問題については、次のようなものが必要だと思います。

class Inspection < ActiveRecord::Base
  has_many :inspection_components
  accepts_nested_attributes_for :inspection_components

  # we only care about validating the components being complete
  # if this inspection is complete. Otherwise we don't care.
  validate :all_components_complete, :if => :complete

  def complete
    self.status == 'complete'
  end

  def all_components_complete
    self.inspection_components.each do |component|
      # as soon as you find an incomplete component, this inspection
      # is INVALID!
      Errors.add("field","msg") if component.status != 'complete'
    end
  end
end

class InspectionComponent < ActiveRecord::Base
  belongs_to :inspection
end
于 2010-09-10T04:45:03.947 に答える
0

を使用しますvalidates_associated

おそらく次のようなものです:

validates_associated :inspection_components

それを検索して、APIを調べます。この方法にもいくつかの便利なオプションがあります。

于 2010-09-10T00:30:57.683 に答える