2017-04-04 55 views
0

我的觀點:如何改變在軌道上改變錯誤信息

<div class="form-group"> 
      <% if @product.errors.details[:amount].any? %> 
      <div class="has-error"> 
       <%= f.label "#{t('product.shineer_irsen')}", class: 'control-label' %> 
       <%= f.number_field :amount, value: 0, min: 0, class: "form-control" %> 
      </div> 
      <% else %>    
      <%= f.label "#{t('product.shineer_irsen')}", class: 'control-label' %> 
      <%= f.number_field :amount, value: 0, min: 0, class: "form-control" %> 
      <% end %> 
     </div> 

我想驗證的輸入字段數量,我想改變其錯誤信息到我的母語。

現在,錯誤消息是 error message

如何改變呢?請幫幫我。

產品型號:

class Product < ApplicationRecord 
    belongs_to :item 
    belongs_to :user 
    belongs_to :branch 
    validates :amount, numericality: {greater_than_or_equal_to: 0} 

    def item_name 
     item.try(:name) 
    end 

    def item_name=(query) 
     self.item = Item.find_by_name(query) if query.present? 
    end 

    def amount=(new_value) 
     if read_attribute(:amount) 
      @old_amount = read_attribute(:amount) 
      write_attribute(:amount, new_value.to_i + @old_amount) 
     else 
      write_attribute(:amount, new_value.to_i) 
     end 
    end 
end 

一些線的本地/ mn.yml

activerecord: 
    attributes: 
    ... 
    errors: 
     models: 
     subcategory: 
      attributes: 
      category_id: 
       invalid: "ahaha" 
       blank: "хоосон байж болохгүй" 
      category: 
       blank: "сонгоогүй байна." 
     product: 
      attributes: 
      amount: 
       greater_than_or_equal_to: 'Оруулах утга 0-ээс их байх ёстой.' 
+0

您應該在型號 –

+0

中驗證我做到了。在模型中:驗證:金額,數值:{greater_than_or_equal_to:0}。但是一旦我收到錯誤,http:// localhost:3000/products/2/edit會變爲http:// localhost:3000/products/2。我的控制器中沒有顯示方法。我刪除了,因爲我不需要它所以,有一些問題:) –

+0

添加您的模型的帖子,我會幫你 –

回答

1

我想你要翻譯「值必須擦菜板大於或等於0」,如果是這樣的情況下,你需要做的是爲語言環境文件創建一個翻譯。在西班牙會是這樣的:

# config/locales/es.yml 
es: 
    activerecord: 
    errors: 
     models: 
     product: 
      attributes: 
      amount: 
       greater_than_or_equal_to: 'What ever you want to say' 

根據您的母語,你必須創建該文件並定義消息,我想你已經在做了,因爲你使用的翻譯:

#{t('product.shineer_irsen')} 

你可以在這裏找到更多的信息:

http://guides.rubyonrails.org/i18n.html#translations-for-active-record-models

+0

我試過了。但沒有工作。仍然收到相同的錯誤信息。 –

0

您可以自定義你從一個模型驗證得到錯誤信息,我在這種情況下,您需要添加到您的型號:

validates :age, numericality: {greater_than_or_equal_to: 0, message: 'Este campo tiene que ser positivo' } 

有了這個,你不需要改變視圖。

+0

驗證是完全正確的。但將消息放在語言環境文件而不是模型上是一種更好的做法。 –

+0

我想我的問題很糟糕。我必須從輸入中獲得大於或等於0的值,並且我必須在模型中進行驗證。我必須這樣做。 –

+0

@CarlosCastillo我在看你的答案,這真的很好(肯定要學習AR的翻譯)。 –