Flowdock

Notes posted by nicb

RSS feed
November 6, 2012 - (>= v3.0.0)
0 thanks

attributes that have the same names as options

For reasons that are beyond my comprehension, this piece of code

class Working

  include ActiveModel::Validations

  attr_accessor :format

  validates :format, :presence => true, :format => { :with => /\AWorking/ }

end

works (NOTE: it has an attribute that has the same name of an option), while this

class NotWorking < ActiveRecord::Base

  validates :format, :presence => true, :format => { :with => /\ANot Working/ }

end

does not (assuming that you have a legacy db in which you can’t change the names of the columns). It throws an ArgumentError at you. However, a crude hack is to add an explicit accessor to the :format method, like this

class WorkingAgain < ActiveRecord::Base

  validates :format, :presence => true, :format => { :with => /\AWorking again/ }

  def format
    read_attribute(:format)
  end

end

Any explanation is welcome.