我有一个产品类,我接受规则属性,规则与选择相关联。
验证在创建时非常有效,问题是当我删除带有选项的关联规则并保存时,需要规则至少有一个选择。
以下是终端中的课程和测试:
product.rb
class Product < ActiveRecord::Base
validates :price, presence: true
validates :name, presence: true, length: { within: 3..25 }
has_many :rules
attr_accessible :name, :description, :price, :category_name, :rules_attributes, :disabled
accepts_nested_attributes_for :rules, allow_destroy: true
end
rule.erb
class Rule < ActiveRecord::Base
validates :name, presence: true, length: { within: 3..40 }
validates :quantity, presence: true, numericality: { greater_than_or_equal_to: 0, only_integer: true }
validates :choice_ids, presence: true
belongs_to :product
has_and_belongs_to_many :choices
attr_accessible :name, :quantity, :choise_ids
end
终端
irb(main):011:0> product = Product.find 2275
Product Load (0.8ms) SELECT "products".* FROM "products" WHERE "products"."id" = $1 ORDER BY name ASC LIMIT 1 [["id", 2275]]
=> #<Product id: 2275, name: "Camarão", description: "", price: #<BigDecimal:623b7d8,'0.65E2',9(18)>, establishment_id: 2, created_at: "2013-10-17 18:37:26", updated_at: "2013-10-18 13:29:49", category_id: 333, disabled: false>
irb(main):012:0> rule = product.rules.find 333
Rule Load (0.8ms) SELECT "rules".* FROM "rules" WHERE "rules"."product_id" = 2275 AND "rules"."id" = $1 LIMIT 1 [["id", 333]]
=> #<Rule id: 333, name: "Adicionais", created_at: "2013-10-22 19:04:11", updated_at: "2013-10-22 19:04:11", quantity: 3, position: 0, product_id: 2275>
irb(main):013:0> rule.choice_ids = [""]
Choice Load (1.1ms) SELECT "choices".* FROM "choices" INNER JOIN "choices_rules" ON "choices"."id" = "choices_rules"."choice_id" WHERE "choices_rules"."rule_id" = 333
(0.4ms) BEGIN
(0.5ms) COMMIT
=> [""]
irb(main):014:0> rule.valid?
=> false
irb(main):015:0> rule.errors
=> #<ActiveModel::Errors:0x000000061b7780 @base=#<Rule id: 333, name: "Adicionais", created_at: "2013-10-22 19:04:11", updated_at: "2013-10-22 19:04:11", quantity: 3, position: 0, product_id: 2275>, @messages={:choice_ids=>["não pode ficar em branco"]}>
irb(main):016:0> product.rules_attributes = {"0"=>{"name"=>"Adicionais", "quantity"=>"3", "_destroy"=>"false", "choice_ids"=>[""], "id"=>"333"}}
Rule Load (0.8ms) SELECT "rules".* FROM "rules" WHERE "rules"."product_id" = 2275 AND "rules"."id" IN (333)
Choice Load (0.8ms) SELECT "choices".* FROM "choices" INNER JOIN "choices_rules" ON "choices"."id" = "choices_rules"."choice_id" WHERE "choices_rules"."rule_id" = 333
(0.4ms) BEGIN
(0.4ms) COMMIT
=> {"0"=>{"name"=>"Adicionais", "quantity"=>"3", "_destroy"=>"false", "choice_ids"=>[""], "id"=>"333"}}
irb(main):017:0> rule
=> #<Rule id: 333, name: "Adicionais", created_at: "2013-10-22 19:04:11", updated_at: "2013-10-22 19:04:11", quantity: 3, position: 0, product_id: 2275>
irb(main):018:0> rule.choices
=> []