簡體   English   中英

驗證Rails中的關聯模型

[英]Validating associated models in Rails

我目前正在研究飲食跟蹤應用程序。 我有一個FoodEntry模型,其中每個實例引用另一個表中的單個food ,並且還引用另一個表中的measurement單位。

class FoodEntry < ActiveRecord::Base
  belongs_to :food
  belongs_to :measurement
  validates :food, presence: { message: 'must exist' }
  ...
end

這很好,但問題是measurements表中的每個條目都已設置(因為我正在使用外部數據)與某種food相關聯,即測量屬於食物,食物有很多測量:

class Food < ActiveRecord::Base
  has_many :measurements
  ...
end

class Measurement < ActiveRecord::Base
  belongs_to :food
  ...
end

我的問題是,驗證我在food_entry引用的具體measurement也是其food.measurements measurement的正確方法是什么?

目前在我的FoodEntry模型中,我這樣做:

validate :measurement_must_be_associated

def measurement_must_be_associated
  unless food.measurements.include? measure
    errors.add(:measurement, 'is not associated with that food')
  end
end

這個自定義驗證有效,但我不確定這是最干凈的方法。

我嘗試這樣做:

validates :measurement, inclusion: { in: food.measurements }

但是當在rails控制台中調用FoodEntry.new(food_id: 1, measurement_id: 1)時,這會給我一個錯誤(實際id不相關):

NameError: undefined local variable or method `food' for FoodEntry (no database connection):Class

in: self.food.measurements在驗證中沒有區別。 救命?

嘗試:

validates :measurement, inclusion: { in: ->(record) { record.food.measurements } }

validates是在類上定義的方法,在聲明類時進行評估。 通常,當包含值在程序啟動之前已知(並且是靜態的)時,傳遞值就足夠了 - 驗證器(在調用validates時創建)只是保存傳遞的對象並在驗證時使用它。

在您的情況下,包含值在創建驗證器時是未知的(並且它們還取決於驗證對象)。 因此,您需要傳遞一個lambda,因此驗證器可以使用它來在運行時獲取包含值。

另請注意,驗證器對象附加到類,而不是特定實例,因此lambda需要具有記錄參數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM