2017-09-07 22 views
0

我使用Rails 5.我有這個在我的模型......在rails 5中,如果我將一個空白字段留空,我怎麼只有一個驗證消息?

belongs_to :crypto_currency 

    validates :crypto_currency, presence: true 

的問題是,當我救我的模型從一種形式,兩個錯誤回來,如果我沒有設定一個值「Crypto_currency」字段...

Crypto currency must exist 
Crypto currency Please select a value for crypto currency. 

這是我的config/locales/en.yml文件。我仍然需要研究如何從「加密貨幣請爲加密貨幣選擇一個值」中刪除「加密貨幣」字樣。錯誤信息,但可以清楚地看到,我只在文件

en: 
    activerecord: 
    errors: 
     models: 
     user_notification: 
      attributes: 
      crypto_currency: 
       blank: "Please select a value for crypto currency." 

中定義一個錯誤消息如何,我只對我的模型的字段中的一個錯誤信息,如果沒有輸入呢?

編輯:在輸入反應評論,這裏就是我展示療法ROR消息

<ul> 
    <% @user_notification.errors.full_messages.each do |message| %> 
    <li><%= message %></li> 
    <% end %> 
    </ul> 
+0

如果你做了一個斷點('byebug')並運行'user_notification..errors.full_messages',你看到了什麼?那麼只是'user_notification.errors'呢? – Leito

+0

你如何在表單中顯示錯誤?球場上的錯誤或者球場上的錯誤都是錯誤的? – Leito

+0

包括我如何dplsya作爲編輯問題的錯誤消息。 – Dave

回答

0

試圖改變你的模型是這樣的:

belongs_to :crypto_currency, optional: true 
validates :crypto_currency, presence: true 

而且

en: 
    activerecord: 
    attributes: 
     user_notification: 
     crypto_currency: "" 
    errors: 
     models: 
     user_notification: 
      attributes: 
      crypto_currency: 
       blank: "Please select a value for crypto currency." 
2

的Rails 5使默認需要belongs_to協會

belongs_to :crypto_currency增加了驗證,所以你並不需要你擁有。

您可以跳過belongs_to默認的驗證這樣的:

belongs_to :crypto_currency, optional: true 

或刪除您自己和自定義默認的錯誤消息

+0

它沒有工作。我刪除了自己的驗證,按照您的建議添加了「required:true」,但出現的錯誤消息是「Crypto currency must exist」,與我想要顯示的自定義對象相反。 – Dave

+0

required:false – chumakoff

+0

如果您刪除自己的驗證,那麼它應該是'belongs_to:crypto_currency,required:true'和'required:「請在語言環境中爲加密貨幣選擇一個值。如果你想保留你的驗證,那麼做'required:false'並且不要改變locales – chumakoff

相關問題