[英]Rails avoiding duplication of database entry(many attributes)
Is there any way to make the model execute an error message like flash[:notice]
?? 有什么方法可以使模型执行错误消息,例如
flash[:notice]
?
I want to avoid entering the same data to my database twice.. 我想避免两次将相同的数据输入到数据库中。
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
This code stop duplicating but it doesn't send any error messages. 此代码停止复制,但不发送任何错误消息。 How can I fix that??
我该如何解决?
I would prefer using a model validation: 我更喜欢使用模型验证:
validates :car_id, uniqueness: { scope: :agent_id }
Take a look at the docs for other options such as allow_nil: true, etc. http://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html 看看该文档的其他选项,如allow_nil:真等http://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html
I would also recommend adding a unique index: 我还建议添加唯一索引:
add_index :name_of_table, [:car_id, :agent_id], unique: true
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.