Tag: 唯一索引

使用Postgres hstore的竞争条件

我有一个表,其中包括许多其他领域的一个hstore DB / schema.rb create_table “requests”, force: true do |t| t.hstore “parameters” end 一些记录具有字段parameters[“company_id”]但不是全部。 我需要做的是确保只使用给定parameters[“company_id”]创建一个Request对象。 可能有多次尝试同时保存记录 – 因此竞争条件。 我在整个表中的hstore寻找唯一的company_id值。 我发现我可以运行一个事务来锁定数据库并检查具有给定parameters[“company_id”]的请求是否存在,如果不创建它。 如果company_id是Request模型上的一个简单字段,我可以这样做: Request.transaction do if Request.find_by(company_id: *id* ) log_duplication_attempt_and_quit else create_new_record log_successful_creation end end 不幸的是它是hstore而我无法改变它。 使用hstore实现这一目标的最佳方法是什么? 我正在寻找快速的东西,因为表中有很多记录。 纯SQL查询没问题 – 遗憾的是我没有足够的SQL背景来弄明白我自己。 这可以为性能编制索引吗? 例: a = Request.new(parameters: {company_id: 567, name: “John”}) b = Request.new(parameters: {name: “Doesn’t have company_id […]

validation在另一个表上具有条件时,数据库中的唯一性validation

当validation有条件但我的要求已经改变时,我在数据库中的唯一性validation中询问了类似的问题,因此这个问题。 当有多个进程时,在Rails中使用唯一性validation是不安全的,除非在数据库上也强制执行约束(在我的情况下是PostgreSQL数据库,所以请参阅http://robots.thoughtbot.com/the-perils-of-uniqueness-validations )。 在我的例子中,唯一性validation是有条件的:只有在另一个模型上的另一个属性变为真时才应该强制执行。 所以我有 class Parent < ActiveRecord::Base # attribute is_published end class Child < ActiveRecord::Base belongs_to :parent validates_uniqueness_of :text, if: :parent_is_published? def parent_is_published? self.parent.is_published end end 所以模型Child有两个属性: parent_id (与Parent关联)和text (文本属性)。 模型Parent有一个属性: is_published (布尔值)。 如果其parent.is_published为true,则所有类型为Child模型的text应该是唯一的。 使用http://robots.thoughtbot.com/the-perils-of-uniqueness-validations中建议的唯一索引太过限制,因为无论is_published的值如何,它都会强制执行约束。 是否有人知道PostgreSQL数据库上依赖于另一个表的“条件”索引? validation具有条件时,数据库中唯一性validation的解决方案是您的条件取决于同一个表上的属性。 还是另一种解决方法?

validation有条件时,数据库中的唯一性validation

当有多个进程时,在Rails中使用唯一性validation是不安全的,除非在数据库上也强制执行约束(在我的情况下是PostgreSQL数据库,所以请参阅http://robots.thoughtbot.com/the-perils-of-uniqueness-validations )。 在我的例子中,唯一性validation是有条件的:只有当模型中的另一个属性变为真时才应强制执行。 所以我有 class Model < ActiveRecord::Base validates_uniqueness_of :text, if: :is_published? def is_published? self.is_published end end 因此模型有两个属性: is_published (布尔值)和text (文本属性)。 对于Model iff is_published为true的所有模型, text应该是唯一的。 使用http://robots.thoughtbot.com/the-perils-of-uniqueness-validations中建议的唯一索引太过限制,因为无论is_published的值如何,它都会强制执行约束。 是否有人知道PostgreSQL数据库中的“条件”索引? 还是另一种解决方法?

Rails唯一性约束和匹配空列的db唯一索引

我的迁移文件中有以下内容 def self.up create_table :payment_agreements do |t| t.boolean :automatic, :default => true, :null => false t.string :payment_trigger_on_order t.references :supplier t.references :seller t.references :product t.timestamps end end 我想确保如果指定了product_id它是唯一的但我也想允许null所以我在我的模型中有以下内容: validates :product_id, :uniqueness => true, :allow_nil => true 工作得很好,但我应该为迁移文件添加一个索引 add_index :payment_agreements, :product_id, :unique => true 显然,当为product_id插入两个空值时,这将抛出exception。 我可以简单地省略迁移中的索引,但是我有可能得到两个PaymentAgreements,其中包含相同的product_id: 并发性和完整性 我的问题是处理这个问题的最佳/最常用方法是什么