Question

Note : Before Answering the question understand this does not have to do anything with attr_accessible or attr_protected the RAILS is in question is 3.1.3 and Ruby 1.9.2p290

Without futher due Here my params that I try to mass assign to DriverLicense Model

 {"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"}

Here the controller code

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

Here the definition of model look like

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

The mass-attributes work for all attributes except 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>

Once can check that on screenshot as well further where the mass-assignment work for all attributes except validity_end_date

enter image description here

Was it helpful?

Solution

Found that the date format is not the same in the both the side
& hence it setting it to nil

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top