【问题标题】:Validating uniqueness of nested data. Using cocoon gem验证嵌套数据的唯一性。使用茧宝石
【发布时间】:2014-04-08 20:59:09
【问题描述】:

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

价格表:

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 gem ('cocoon', '~> 1.2.3' - https://github.com/nathanvda/cocoon) 并找到这篇文章来帮助我,但我真的很难理解我应该在哪里添加代码?

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

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

【问题讨论】:

  • @BroiSatse 由于某种原因不适用于嵌套表单。
  • 你在用cocoon吗?
  • 啊是茧(而不是康康 - 我编辑了我的问题)。当我添加此代码时,验证:定价,唯一性:{ 范围::product_id,消息:“不能多次添加相同的产品。”我收到此错误 - ClientsController#create undefined method `attributes' 中的 NoMethodError #<:associations::collectionproxy::activerecord_associations_collectionproxy_pricing:0x859 cd30>
  • 您需要将此添加到 Pricing 模型 - 我会发布答案。

标签: validation ruby-on-rails-4 associations nested-forms cocoon-gem


【解决方案1】:

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

class Pricing < AR::Base

  validates :product_id, uniqueness: true

end

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-24
    • 1970-01-01
    相关资源
    最近更新 更多