有些人可以解释Rails质量分配和验证的这种奇怪的行为

时间:2013-01-01 08:54:11

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.1 mass-assignment

注意:在回答问题之前,了解这不需要对 attr_accessible attr_protected 做任何事情,RAILS有问题 3.1.3 和Ruby 1.9.2p290

没有进一步的到期在这里,我试图大量分配给DriverLicense模型

 {"utf8"=>"✓",
 "authenticity_token"=>"cKhruPzVvBK63bqCQPFY8xPZb12V5lhLPOpXgjIToJk=",
 "driver_license"=>
  {"license_number"=>"LICENCE-001",
   "license_class"=>"A-CLASS",
   "validity_start_date"=>"02/01/2011",
   "validity_end_date"=>"08/24/2011",
   "issuing_authority"=>"RTO",
   "remarks"=>"Remarks .."},
 "save_button"=>"Save",
 "action"=>"create",
 "controller"=>"driver_licenses",
 "driver_id"=>"2"}

这里是控制器代码

@driver_license = @driver.driver_licenses.new(params[:driver_license])

这里模型的定义看起来像

class DriverLicense < ActiveRecord::Base
    acts_as_tenant(:tenant)
    validates :driver_id,:license_number,:validity_start_date,:validity_end_date,:presence => true  
    validate :date_validity ,:if => :is_date_present?

    validate :overlapping_validity,:if => :validity_start_date_present? 

    belongs_to :driver

    scope :active_licenses , where('validity_start_date <= ? and validity_end_date >= ?',Date.today,Date.today) 


    .... ....
    .... ....

    private
    def is_date_present?
        validity_start_date.present? and validity_end_date.present?
    end 


    def date_validity
      errors.add(:validity_start_date,"must be earlier then validity end date") if validity_start_date > validity_end_date
    end

    def validity_start_date_present?
        validity_start_date.present?
    end 


    def overlapping_validity
        arel =  self.class.where('validity_end_date >= ?',validity_start_date).where('driver_id = ?',driver_id)     
        arel = arel.where('id != ?',id) if id.present?      
        unless arel.count.zero?
            errors.add(:validity_start_date,"overLapping date with other licenses")
        end 
    end 

end

mass-attributes适用于除validity_end_date

之外的所有属性
#<DriverLicense id: nil, driver_id: 2, license_number: "LICENCE-001", license_class: "A-CLASS", issuing_authority: "RTO", validity_start_date: "2011-01-02", validity_end_date: nil, remarks: "Remarks ..", tenant_id: 2, created_at: nil, updated_at: nil>

一旦可以检查屏幕截图以及除 validity_end_date

之外的所有属性的质量分配工作

enter image description here

1 个答案:

答案 0 :(得分:0)

发现两侧的日期格式不一样 &安培;因此它将其设置为零