本文介绍了验证嵌套数据的唯一性。使用宝石茧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有HAS_MANY pricings客户端模式。

I currently have a Client model that has_many pricings.

Pricings表:

Pricings table:

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

Pricings模型:

Pricings model:

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

正如你可以在上面看到,当我创建,保存,更新客户端的pricings应该是present。我现在想的是,以确保pricings有一个独特的product_id(没有两个pricings可以有相同的product_id。)

As you can see above, when I create,save,update a client the pricings should be present. What I want now is to make sure that the pricings have a unique product_id (no two pricings can have the same product_id.)

我利用茧宝石('茧'的'〜> 1.2.3' - ),并发现这篇文章帮助我,但即时通讯真正努力来理解我要补充的code?

I'm making use of the cocoon gem ('cocoon', '~> 1.2.3' - https://github.com/nathanvda/cocoon) and found this article to help me out, but im really struggling to understand where I should add the code?

链接到code我不明白:的

Link to code I don't understand: http://techbrownbags.wordpress.com/2014/02/05/rails-validation-of-cocoon-nested-forms/

我怎样才能适应了code到我的情况?

How can I adapt that code to my situation?

推荐答案

您需要验证添加到您的定价模式:

You need to add a validation to your Pricing model:

class Pricing < AR::Base

  validates :product_id, uniqueness: true

end

请注意,即使如此,仍然有机会式两份将在数据库中(特别是当你使用多线程服务器像麒麟,或您的应用程序上multimple服务器上运行)输入。为了100%肯定,你就来介绍分贝约束。你可以用简单的迁移做到这一点:

Note that even with this, there is still a chance that two duplicates will be entered in your database (especially when you use multithreaded server like unicorn or your app is running on multimple servers). To be 100% sure, you have to introduce db constraint. You can do this with simple migration:

add_index :pricings, :product_id, :unique => true

这篇关于验证嵌套数据的唯一性。使用宝石茧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-09 14:38