【发布时间】: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