[英]How do I use the value of an attribute within a model? Ruby on Rails
基本上,我有一個degree_type
模型,它具有三個屬性: degree_type
, awarded_by
和date_awarded
。
有兩個值數組應該對awarded_by
有效。 degree_type
的兩個有效值是"one"
和"two"
, awarded_by
取決於"one"
和"two"
。
如果degree_type
為"one"
(用戶將輸入的值為"one"
),則我想將awarded_by
的有效值設為array_one
。 如果degree_type
的值為"two"
,則我想awarded_by
的有效值為array_two
。
這是到目前為止的代碼:
class Degree < ActiveRecord::Base
extend School
validates :degree_type, presence: true,
inclusion: { in: ["one",
"two"],
message: "is not a valid degree type"
}
validates :awarded_by, presence: true,
inclusion: { in: Degree.schools(awarded_by_type) }
end
Degree.schools
根據學位類型輸出一個數組,因此Degree.schools("one")
將返回array_one
,其中
array_one = ['school01', 'school02'...]
我的問題是,我不知道如何訪問模型中的degree_type
的值。
我在下面嘗試的方法不起作用:
validates :awarded_by, presence: true,
inclusion: { in: Degree.schools(:degree_type) }
我嘗試使用before_type_cast
但是我使用不正確,或者出現了另一個問題,因為我也無法使用它。
當我測試時,我得到:
An object with the method #include? or a proc, lambda or symbol is required, and must be supplied as the :in (or :within) option of the configuration hash
幫幫我? :)如果需要更多信息,請告訴我。
編輯:為此,我再次檢查了這不是我的Degree.schools方法起作用的-如果我進入rails控制台並嘗試Degree.schools("one")
或Degree.schools("two")
我會做得到我應該得到的數組。 :)
再次編輯:當我嘗試awarded_by
的答案時,在awarded_by
不正確的情況下出現錯誤,因為在這些情況下, valid_awarded_by_values
為nil
,沒有include?
nil對象的方法。 因此,我添加了一個if語句來檢查valid_awarded_by_values
是否為nil
(以便return
是否為nil
),從而解決了該問題!
我將其放在方法中,在except語句之前和valid_awarded_by_values聲明之后:
if valid_awarded_by_values.nil?
error_msg = "is not a valid awarded_by"
errors.add(:awarded_by, error_msg)
return
end
最簡單的方法是編寫一個自定義驗證方法, 如Active Record Validations Rails Guide中所述 。
在您的情況下,可能看起來像這樣:
class Degree < ActiveRecord::Base
validate :validate_awarded_by_inclusion_dependent_on_degree_type
# ...
def validate_awarded_by_inclusion_dependent_on_degree_type
valid_awarded_by_values = Degree.schools(degree_type)
unless valid_awarded_by_values.include?(awarded_by)
error_msg = "must be " << valid_awarded_by_values.to_sentence(two_words_connector: ' or ', last_word_connector: ', or ')
errors.add(:awarded_by, error_msg)
end
end
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.