2014-12-03 100 views
2

基本上,我有一個模型,度,它有三個屬性:degree_type,awarded_bydate_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_valuesnil並有一個零對象沒有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 

回答

0

最簡單的方法將是寫一個自定義的驗證方法,as described in the 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 
+0

當我試圖用這個,我的測試告訴我: NoMethodError: 未定義的方法'包括「?對於零:NilClass 我猜測,無論什麼價值被納入Degree.schools(degree_type)不是實際值,應該是一個字符串 - 你知道如何訪問? (對不起,我在發佈之前發佈了它,請儘快輸入) – 2014-12-03 23:20:30

+0

是的,問題是'Degree.schools'返回'nil'。您可以使用['logger.debug'](http://guides.rubyonrails.org/debugging_rails_applications.html#the-logger)將任何值寫入Rails日誌。 – 2014-12-03 23:39:03

+0

我想通了,編輯了我的問題 - 我只需要添加if語句來檢查Degree.schools是否無法解決問題。 :D否則它看起來工作得很好,畢竟我並不需要確切的值。 :) 非常感謝你的幫助! – 2014-12-03 23:56:10