2015-10-20 106 views
0

有什麼辦法讓模型執行一個錯誤信息,如flash[:notice]Rails避免重複數據庫輸入(很多屬性)

我想避免輸入相同的數據到我的數據庫兩次..

before_save :no_duplication 

private 

    def no_duplication 
     if CarPrice.where(:car_id => self.car_id).where(:agent_id => self.agent_id).blank? 
      return true 
     else 
      return false 
     end 
    end 

這段代碼複製停止,但它不發送任何錯誤消息。我該如何解決這個問題?

+0

的可能的複製[訪問導軌閃光\ [:通知\]在一個模型(http://stackoverflow.com/questions/2701932/accessing-rails-flashnotice-in-a-model) – Pavan

回答

4

我寧願用模型驗證:

validates :car_id, uniqueness: { scope: :agent_id } 

看看該文檔的其他選項,如allow_nil:真等http://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html

我還建議增加一個唯一索引:

add_index :name_of_table, [:car_id, :agent_id], unique: true 
+0

驗證:car_id,唯一性:{scope::agent_id} 您的意思是這行代替我的整個代碼? – amronrails

+0

是的 - 這就是我會做的。我沒有看到您需要使用當前的before_save方法。 –