Rails避免重复数据库输入(很多属性)
问题描述:
有什么办法让模型执行一个错误信息,如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
这段代码复制停止,但它不发送任何错误消息。我该如何解决这个问题?
答
我宁愿用模型验证:
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方法。 –
的可能的复制[访问导轨闪光\ [:通知\]在一个模型(http://stackoverflow.com/questions/2701932/accessing-rails-flashnotice-in-a-model) – Pavan