Written by Sean Behan on Sun Jun 17th 2012

You might use the attr_accessible method to create getters and setters for a class that has attributes which don't map directly to corresponding fields in a database. For example let's take the scenario where you are processing a credit card transaction. You don't want to save the credit card details, such as card number and verification value etc, however you still want to use these attributes in a form and you want to perform validations on them.

class CreditCardPurchase < ActiveRecord::Base
  attr_accessor :number, :cvv
end

The only probem that I've run into is using the attr_accessor on datetime select form fields. Rails won't be able to determine the "klass" and will spit out a nasty error. Looks there is some discussion around this bug. I've got another post about this topic http://seanbehan.com/ruby-on-rails/problem-slash-bug-in-rails-with-attr_accessor-and-datetime-select-fields/ but unfortunately not a whole lot of resultion :(


Tagged with..
#attr_accessor #forms #getters #Rails #setters #troubleshooting #validations #virtual attributes #Ruby on Rails

Just finishing up brewing up some fresh ground comments...