0

我目前有一个具有多个定价的客户端模型。

价格表:

create_table "pricings", force: true do |t|
    t.integer  "product_id"
    t.integer  "client_id"
    t.decimal  "unit_price"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

定价模型:

class Pricing < ActiveRecord::Base
  belongs_to :client
  belongs_to :product  
  validates :unit_price, presence: true  
end

客户型号:

class Client < ActiveRecord::Base
  has_many :deliveries
  has_many :collections
  has_many :pricings
  accepts_nested_attributes_for :pricings, allow_destroy: true

  scope :order_by_name, -> { order('lower(name)') }

  validates :name, :address, :vat_number, presence: true 
  validates :pricings,  presence:  { :message => ": Products must be added for a client before you can save." }
end

正如您在上面看到的,当我创建、保存、更新客户端时,应该显示定价。我现在想要的是确保定价具有唯一的 product_id(没有两个定价可以具有相同的 product_id。)

我正在使用茧宝石('cocoon','~> 1.2.3' - https://github.com/nathanvda/cocoon)并找到这篇文章来帮助我,但我真的很难理解在哪里我应该添加代码吗?

链接到我不明白的代码:http: //techbrownbags.wordpress.com/2014/02/05/rails-validation-of-cocoon-nested-forms/

如何使该代码适应我的情况?

4

1 回答 1

1

您需要向定价模型添加验证:

class Pricing < AR::Base

  validates :product_id, uniqueness: true

end

请注意,即使这样,仍然有可能在您的数据库中输入两个重复项(尤其是当您使用像 unicorn 这样的多线程服务器或您的应用程序在多个服务器上运行时)。要 100% 确定,您必须引入 db 约束。您可以通过简单的迁移来做到这一点:

add_index :pricings, :product_id, :unique => true  
于 2014-04-09T11:16:44.347 回答