基本上,我有一個模型,度,它有三個屬性:degree_type
,awarded_by
和date_awarded
。如何使用模型中屬性的值? Ruby on Rails
有兩個數組值應該對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
其中
array_one = ['school01', 'school02'...]
我的問題是輸出視度類型的數組,所以Degree.schools("one")
將返回array_one
,我不知道如何在模型中訪問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方法演戲了 - 如果我進入軌道控制檯,並嘗試Degree.schools("one")
或Degree.schools("two")
我得到的陣列我應該得到的。 :)再次
編輯:當我試圖@喬丹的回答,我的情況下awarded_by
是不正確的,因爲在這些情況下,valid_awarded_by_values
是nil
並有一個零對象沒有include?
方法錯誤。因此,我添加了一條if語句,檢查valid_awarded_by_values
是否爲nil
(如果是,則爲return
),並解決了問題!
我把這個方法裏面,除非聲明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
當我試圖用這個,我的測試告訴我: NoMethodError: 未定義的方法'包括「?對於零:NilClass 我猜測,無論什麼價值被納入Degree.schools(degree_type)不是實際值,應該是一個字符串 - 你知道如何訪問? (對不起,我在發佈之前發佈了它,請儘快輸入) – 2014-12-03 23:20:30
是的,問題是'Degree.schools'返回'nil'。您可以使用['logger.debug'](http://guides.rubyonrails.org/debugging_rails_applications.html#the-logger)將任何值寫入Rails日誌。 – 2014-12-03 23:39:03
我想通了,編輯了我的問題 - 我只需要添加if語句來檢查Degree.schools是否無法解決問題。 :D否則它看起來工作得很好,畢竟我並不需要確切的值。 :) 非常感謝你的幫助! – 2014-12-03 23:56:10