有没有办法让模型执行像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
此代码停止重复,但不会发送任何错误消息。我该如何解决?
答案 0 :(得分:4)
我更喜欢使用模型验证:
validates :car_id, uniqueness: { scope: :agent_id }
查看其他选项的文档,例如allow_nil:true等。http://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html
我还建议添加一个唯一索引:
add_index :name_of_table, [:car_id, :agent_id], unique: true