[英]Rails avoiding duplication of database entry(many attributes)
有什么方法可以使模型執行錯誤消息,例如flash[:notice]
?
我想避免兩次將相同的數據輸入到數據庫中。
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
此代碼停止復制,但不發送任何錯誤消息。 我該如何解決?
我更喜歡使用模型驗證:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.